diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..5a599cd --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +* +!Dockerfile +!templates/ms-style/** +!framework-views/** diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 0000000..6ad7963 --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,4 @@ +self-hosted-runner: + labels: + - ubuntu-26.04 + - ubuntu-26.04-arm diff --git a/.github/workflows/container.yml b/.github/workflows/container.yml new file mode 100644 index 0000000..4e99c4e --- /dev/null +++ b/.github/workflows/container.yml @@ -0,0 +1,92 @@ +name: Container validation + +on: + workflow_call: + +permissions: + contents: read + +jobs: + container: + name: Native ${{ matrix.arch.architecture }} + runs-on: ${{ matrix.arch.runner }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + arch: + - { architecture: amd64, runner: ubuntu-26.04 } + - { architecture: arm64, runner: ubuntu-26.04-arm } + steps: + - name: Checkout + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Install OCI transfer tool + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends skopeo + + - name: Enable OCI exporter + run: docker buildx create --driver docker-container --use + + - name: Build once and validate exported candidate on native CPU + shell: pwsh + env: + TARGET_PLATFORM: linux/${{ matrix.arch.architecture }} + TARGET_ARCH: ${{ matrix.arch.architecture }} + EVENT_NAME: ${{ github.event_name }} + REF_TYPE: ${{ github.ref_type }} + REF_NAME: ${{ github.ref_name }} + RUN_NUMBER: ${{ github.run_number }} + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + Import-Module ./tools/DocfxImage.psm1 -Force + $null = Test-DocfxVersionConsistency + $engineVersion = if ($env:EVENT_NAME -ceq 'push' -and $env:REF_TYPE -ceq 'tag') { + Resolve-ReleaseTagVersion -Tag $env:REF_NAME + } else { + "0.0.0-ci.$($env:RUN_NUMBER)" + } + ./BuildAndPushDocfxImage.ps1 ` + -BuildOnly ` + -EngineVersion $engineVersion ` + -Platform $env:TARGET_PLATFORM ` + -RequireNative ` + -ArchivePath "./artifacts/docfx.$($env:TARGET_ARCH).oci.tar" ` + -MetadataFile './artifacts/docfx-image.json' ` + -PassThru | Format-List + + - name: Preserve exact tested OCI content and native verification record + if: github.event_name == 'push' && github.ref_type == 'tag' + uses: actions/upload-artifact@v7 + with: + name: container-${{ matrix.arch.architecture }} + path: artifacts/* + compression-level: 0 + if-no-files-found: error + retention-days: 1 + + - name: Preserve PR validation metadata without large container archives + if: github.event_name != 'push' || github.ref_type != 'tag' + uses: actions/upload-artifact@v7 + with: + name: container-metadata-${{ matrix.arch.architecture }}-${{ github.run_attempt }} + path: artifacts/*.json + if-no-files-found: error + retention-days: 7 + + quality: + name: Both native architectures verified + if: always() + needs: [container] + runs-on: ubuntu-26.04 + steps: + - env: + RESULT: ${{ needs.container.result }} + run: test "$RESULT" = success diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..eed0200 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,137 @@ +name: Deploy Docker Hub images + +on: + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: Published latest release tag to recover (existing verified artifacts only) + required: true + type: string + +permissions: + contents: read + +concurrency: + group: docfx-production + cancel-in-progress: false + +jobs: + resolve: + name: Resolve approved published release + runs-on: ubuntu-26.04 + timeout-minutes: 15 + outputs: + sha: ${{ steps.resolve.outputs.sha }} + engine-version: ${{ steps.resolve.outputs.engine-version }} + deployment-sha: ${{ steps.resolve.outputs.deployment-sha }} + steps: + - name: Checkout deployment tooling from main + uses: codebeltnet/git-checkout@v1 + with: + ref: main + + - id: resolve + name: Resolve release identity, ancestry, and asset inventory + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ github.event.release.tag_name || inputs.tag }} + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $deploymentSha = (& git rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $deploymentSha -cnotmatch '^[0-9a-f]{40}$') { + throw 'Unable to resolve deployment tooling revision from main.' + } + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "deployment-sha=$deploymentSha" -Encoding utf8NoBOM + ./tools/Invoke-DocfxRelease.ps1 -Command Resolve + + - name: Preserve resolved release identity + uses: actions/upload-artifact@v7 + with: + name: resolved-release + path: resolved/* + retention-days: 7 + if-no-files-found: error + + verify: + name: Verify durable OCI release artifact + needs: [resolve] + runs-on: ubuntu-26.04 + timeout-minutes: 45 + permissions: + contents: read + actions: read + steps: + - name: Checkout pinned deployment tooling + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ needs.resolve.outputs.deployment-sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Download resolved release identity + uses: actions/download-artifact@v8 + with: + name: resolved-release + path: resolved + + - name: Reconstruct and validate release run, native results, checksums, and attestations + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: ./tools/Invoke-DocfxRelease.ps1 -Command Restore + + - name: Verify reconstructed OCI archive with Codebelt verifier + uses: codebeltnet/oci-artifact-verify@v1 + with: + archive-path: ${{ github.workspace }}/out/docfx.oci.tar + checksum-path: ${{ github.workspace }}/out/docfx.oci.tar.sha256 + version: ${{ needs.resolve.outputs.engine-version }} + revision: ${{ needs.resolve.outputs.sha }} + + publish: + name: Promote verified OCI image to Docker Hub + needs: [resolve, verify] + runs-on: ubuntu-26.04 + timeout-minutes: 60 + environment: Production + permissions: + contents: read + actions: read + steps: + - name: Checkout pinned deployment tooling + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ needs.resolve.outputs.deployment-sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Download resolved release identity + uses: actions/download-artifact@v8 + with: + name: resolved-release + path: resolved + + - name: Install OCI transfer tool + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends skopeo + + - name: Authenticate, promote without rebuild, and verify published tags + env: + GH_TOKEN: ${{ github.token }} + DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} + DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} + run: | + set -euo pipefail + export REGISTRY_AUTH_FILE="$RUNNER_TEMP/docfx-auth.json" + trap 'rm -f "$REGISTRY_AUTH_FILE"' EXIT + printf '%s' "$DOCKERHUB_TOKEN" | skopeo login --authfile "$REGISTRY_AUTH_FILE" --username "$DOCKERHUB_USERNAME" --password-stdin docker.io + pwsh -NoProfile -File ./tools/Invoke-DocfxRelease.ps1 -Command Publish diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml new file mode 100644 index 0000000..57a163a --- /dev/null +++ b/.github/workflows/pr.yml @@ -0,0 +1,227 @@ +name: PR Flow + +on: + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +env: + # Routing tests need an NGINX image that forked PRs can pull anonymously. + TEST_NGINX_IMAGE: ghcr.io/nginx/nginx-unprivileged:1.31-alpine + +concurrency: + group: pr-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + workflow-validation: + name: Workflow syntax and version contracts + runs-on: ubuntu-26.04 + timeout-minutes: 10 + steps: + - name: Checkout + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Validate DocFX version consistency + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + Import-Module ./tools/DocfxImage.psm1 -Force + $version = Test-DocfxVersionConsistency + Write-Host "DocFX version consistency verified: $version" + + - name: Validate GitHub Actions workflow definitions + run: | + set -euo pipefail + ARCHIVE="$RUNNER_TEMP/actionlint.tar.gz" + curl -fsSL -o "$ARCHIVE" 'https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz' + echo '8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 '"$ARCHIVE" | sha256sum -c - + tar -xzf "$ARCHIVE" -C "$RUNNER_TEMP" actionlint + "$RUNNER_TEMP/actionlint" + + unit-tests: + name: Unit tests and coverage (${{ matrix.os }}) + runs-on: ${{ matrix.runner }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + - { os: linux, runner: ubuntu-26.04 } + - { os: windows, runner: windows-2025 } + steps: + - name: Checkout + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Install Pester 5 + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + Install-PSResource -Name Pester -Version '5.7.1' -Repository PSGallery -TrustRepository -Scope CurrentUser + + - name: Run unit tests, 100% coverage, and OCI contract suites + shell: pwsh + run: ./tools/Invoke-UnitTests.ps1 -CoverageOutputDir ./coverage + + - name: Upload coverage reports + if: always() + uses: actions/upload-artifact@v7 + with: + name: unit-coverage-${{ matrix.os }}-${{ github.run_attempt }} + path: coverage/*.xml + if-no-files-found: ignore + retention-days: 7 + + framework-views: + name: Native framework-views regression (${{ matrix.os }}) + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - { os: linux, runner: ubuntu-26.04, testRouting: true } + - { os: windows, runner: windows-2025, testRouting: false } + steps: + - name: Checkout + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Install DocFX CLI + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + Import-Module ./tools/DocfxImage.psm1 -Force + $docfxVersion = Get-DocfxDefaultVersion + & dotnet tool install --global docfx --version $docfxVersion + if ($LASTEXITCODE -ne 0) { throw "Failed to install DocFX CLI $docfxVersion." } + + - name: Run native framework-views regression tests + shell: pwsh + env: + TEST_ROUTING: ${{ matrix.testRouting }} + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $testArgs = @{} + if ($env:TEST_ROUTING -ceq 'true') { + $testArgs.TestRouting = $true + $testArgs.NginxImage = $env:TEST_NGINX_IMAGE + } + ./tests/framework-view/Test-FrameworkViews.ps1 @testArgs + + browser-and-routing: + name: Browser and HTTP routing regression + runs-on: ubuntu-26.04 + timeout-minutes: 30 + steps: + - name: Checkout + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Setup Node.js + uses: actions/setup-node@v7 + with: + node-version: '24' + cache: npm + cache-dependency-path: tests/framework-view/package-lock.json + + - name: Install DocFX CLI + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + Import-Module ./tools/DocfxImage.psm1 -Force + $docfxVersion = Get-DocfxDefaultVersion + & dotnet tool install --global docfx --version $docfxVersion + if ($LASTEXITCODE -ne 0) { throw "Failed to install DocFX CLI $docfxVersion." } + + - name: Install Playwright and Chromium + working-directory: tests/framework-view + run: | + npm ci + npx playwright install --with-deps chromium + + - name: Run packaged generator, NGINX routing, and Playwright browser tests + shell: pwsh + run: ./tests/framework-view/Test-FrameworkView.ps1 -NginxImage $env:TEST_NGINX_IMAGE + + cuemon-acceptance: + name: Cuemon acceptance scenario + runs-on: ubuntu-26.04 + timeout-minutes: 30 + steps: + - name: Checkout + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Install DocFX CLI + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + Import-Module ./tools/DocfxImage.psm1 -Force + $docfxVersion = Get-DocfxDefaultVersion + & dotnet tool install --global docfx --version $docfxVersion + if ($LASTEXITCODE -ne 0) { throw "Failed to install DocFX CLI $docfxVersion." } + + - name: Run pinned Cuemon.Kernel and Cuemon.IO acceptance tests + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $scratch = Join-Path $env:RUNNER_TEMP 'docfx-cuemon-acceptance' + $consumer = Join-Path $scratch 'consumer' + $output = Join-Path $scratch 'output' + & git clone --single-branch --branch v11.0.0/docfx https://github.com/codebeltnet/cuemon.git $consumer + if ($LASTEXITCODE -ne 0) { throw 'Unable to clone Cuemon acceptance fixture.' } + & git -C $consumer checkout --detach 53875b1bbb778067a0a029b87861efdb0b78a8b5 + if ($LASTEXITCODE -ne 0) { throw 'Unable to checkout pinned Cuemon fixture revision.' } + ./tests/framework-view/cuemon/Build-CuemonFixture.ps1 -ConsumerRoot $consumer -OutputRoot $output + ./tests/framework-view/cuemon/Test-CuemonFrameworkViews.ps1 -Workspace $output -NginxImage $env:TEST_NGINX_IMAGE + + containers: + uses: ./.github/workflows/container.yml + + quality: + name: Required quality gate + if: always() + needs: [workflow-validation, unit-tests, framework-views, browser-and-routing, cuemon-acceptance, containers] + runs-on: ubuntu-26.04 + steps: + - env: + RESULTS: ${{ toJSON(needs) }} + run: echo "$RESULTS" | jq -e 'all(.[]; .result == "success")' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..2c7f5f1 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,308 @@ +name: Release Flow + +on: + push: + tags: ['v*'] + +permissions: + contents: read + +env: + # Use the same anonymously pullable NGINX image as PR validation. + TEST_NGINX_IMAGE: ghcr.io/nginx/nginx-unprivileged:1.31-alpine + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + validate: + name: Validate release tag and contracts + runs-on: ubuntu-26.04 + timeout-minutes: 10 + steps: + - name: Checkout tagged commit + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Validate release tag, revision, and DocFX version consistency + shell: pwsh + run: ./tools/Invoke-DocfxRelease.ps1 -Command ValidateTag + + - name: Validate GitHub Actions workflow definitions + run: | + set -euo pipefail + ARCHIVE="$RUNNER_TEMP/actionlint.tar.gz" + curl -fsSL -o "$ARCHIVE" 'https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz' + echo '8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 '"$ARCHIVE" | sha256sum -c - + tar -xzf "$ARCHIVE" -C "$RUNNER_TEMP" actionlint + "$RUNNER_TEMP/actionlint" + + unit-tests: + name: Unit tests and coverage (${{ matrix.os }}) + needs: [validate] + runs-on: ${{ matrix.runner }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + - { os: linux, runner: ubuntu-26.04 } + - { os: windows, runner: windows-2025 } + steps: + - name: Checkout tagged commit + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Install Pester 5 + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + Install-PSResource -Name Pester -Version '5.7.1' -Repository PSGallery -TrustRepository -Scope CurrentUser + + - name: Run unit tests, 100% coverage, and OCI contract suites + shell: pwsh + run: ./tools/Invoke-UnitTests.ps1 -CoverageOutputDir ./coverage + + framework-views: + name: Native framework-views regression (${{ matrix.os }}) + needs: [validate] + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - { os: linux, runner: ubuntu-26.04, testRouting: true } + - { os: windows, runner: windows-2025, testRouting: false } + steps: + - name: Checkout tagged commit + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Install DocFX CLI + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + Import-Module ./tools/DocfxImage.psm1 -Force + $docfxVersion = Get-DocfxDefaultVersion + & dotnet tool install --global docfx --version $docfxVersion + if ($LASTEXITCODE -ne 0) { throw "Failed to install DocFX CLI $docfxVersion." } + + - name: Run native framework-views regression tests + shell: pwsh + env: + TEST_ROUTING: ${{ matrix.testRouting }} + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $testArgs = @{} + if ($env:TEST_ROUTING -ceq 'true') { + $testArgs.TestRouting = $true + $testArgs.NginxImage = $env:TEST_NGINX_IMAGE + } + ./tests/framework-view/Test-FrameworkViews.ps1 @testArgs + + browser-and-routing: + name: Browser and HTTP routing regression + needs: [validate] + runs-on: ubuntu-26.04 + timeout-minutes: 30 + steps: + - name: Checkout tagged commit + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Setup Node.js + uses: actions/setup-node@v7 + with: + node-version: '24' + cache: npm + cache-dependency-path: tests/framework-view/package-lock.json + + - name: Install DocFX CLI + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + Import-Module ./tools/DocfxImage.psm1 -Force + $docfxVersion = Get-DocfxDefaultVersion + & dotnet tool install --global docfx --version $docfxVersion + if ($LASTEXITCODE -ne 0) { throw "Failed to install DocFX CLI $docfxVersion." } + + - name: Install Playwright and Chromium + working-directory: tests/framework-view + run: | + npm ci + npx playwright install --with-deps chromium + + - name: Run packaged generator, NGINX routing, and Playwright browser tests + shell: pwsh + run: ./tests/framework-view/Test-FrameworkView.ps1 -NginxImage $env:TEST_NGINX_IMAGE + + cuemon-acceptance: + name: Cuemon acceptance scenario + needs: [validate] + runs-on: ubuntu-26.04 + timeout-minutes: 30 + steps: + - name: Checkout tagged commit + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Install DocFX CLI + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + Import-Module ./tools/DocfxImage.psm1 -Force + $docfxVersion = Get-DocfxDefaultVersion + & dotnet tool install --global docfx --version $docfxVersion + if ($LASTEXITCODE -ne 0) { throw "Failed to install DocFX CLI $docfxVersion." } + + - name: Run pinned Cuemon.Kernel and Cuemon.IO acceptance tests + shell: pwsh + run: | + Set-StrictMode -Version Latest + $ErrorActionPreference = 'Stop' + $scratch = Join-Path $env:RUNNER_TEMP 'docfx-cuemon-acceptance' + $consumer = Join-Path $scratch 'consumer' + $output = Join-Path $scratch 'output' + & git clone --single-branch --branch v11.0.0/docfx https://github.com/codebeltnet/cuemon.git $consumer + if ($LASTEXITCODE -ne 0) { throw 'Unable to clone Cuemon acceptance fixture.' } + & git -C $consumer checkout --detach 53875b1bbb778067a0a029b87861efdb0b78a8b5 + if ($LASTEXITCODE -ne 0) { throw 'Unable to checkout pinned Cuemon fixture revision.' } + ./tests/framework-view/cuemon/Build-CuemonFixture.ps1 -ConsumerRoot $consumer -OutputRoot $output + ./tests/framework-view/cuemon/Test-CuemonFrameworkViews.ps1 -Workspace $output -NginxImage $env:TEST_NGINX_IMAGE + + containers: + needs: [validate] + uses: ./.github/workflows/container.yml + + assemble: + name: Assemble and verify multi-platform OCI index + needs: [validate, unit-tests, framework-views, browser-and-routing, cuemon-acceptance, containers] + runs-on: ubuntu-26.04 + timeout-minutes: 45 + steps: + - name: Checkout tagged commit + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Install .NET SDK + uses: codebeltnet/install-dotnet@v3 + with: + versionPrecision: patch + + - name: Download verified native OCI artifacts + uses: actions/download-artifact@v8 + with: + pattern: container-* + path: inputs + + - id: assemble + name: Assemble exact native-verified AMD64 and ARM64 OCI index + shell: pwsh + run: ./tools/Invoke-DocfxRelease.ps1 -Command Assemble + + - id: verify_oci + name: Verify assembled OCI archive with Codebelt verifier + uses: codebeltnet/oci-artifact-verify@v1 + with: + archive-path: ${{ github.workspace }}/out/docfx.oci.tar + checksum-path: ${{ github.workspace }}/out/docfx.oci.tar.sha256 + version: ${{ steps.assemble.outputs.version }} + revision: ${{ github.sha }} + + - name: Confirm verifier digest matches assembled release metadata + shell: pwsh + env: + ASSEMBLED_DIGEST: ${{ steps.assemble.outputs.digest }} + VERIFIED_DIGEST: ${{ steps.verify_oci.outputs.digest }} + run: | + if ($env:ASSEMBLED_DIGEST -cne $env:VERIFIED_DIGEST) { + throw "OCI verifier digest '$($env:VERIFIED_DIGEST)' does not match assembled digest '$($env:ASSEMBLED_DIGEST)'." + } + + - name: Split release assets below GitHub per-file limit + shell: pwsh + run: ./tools/Invoke-DocfxRelease.ps1 -Command Split + + - name: Upload durable release asset bundle + uses: actions/upload-artifact@v7 + with: + name: release-assets + path: assets/* + compression-level: 0 + retention-days: 1 + if-no-files-found: error + + release: + name: Create draft release + needs: [validate, unit-tests, framework-views, browser-and-routing, cuemon-acceptance, containers, assemble] + runs-on: ubuntu-26.04 + timeout-minutes: 15 + permissions: + actions: write + contents: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RELEASE_TAG: ${{ github.ref_name }} + steps: + - name: Checkout tagged commit + uses: codebeltnet/git-checkout@v1 + with: + ref: ${{ github.sha }} + + - name: Download verified release assets + uses: actions/download-artifact@v8 + with: + name: release-assets + path: release + + - name: Create draft GitHub release with durable OCI assets + run: | + set -euo pipefail + gh release create "$RELEASE_TAG" release/* --verify-tag --draft --generate-notes --title "$RELEASE_TAG" + + - name: Verify durable release assets before cleaning transient CI copies + shell: pwsh + run: ./tools/Invoke-DocfxRelease.ps1 -Command VerifyDraftAssets -ReleaseDir release + + - name: Remove transient workflow artifacts after durable verification + continue-on-error: true + run: | + set -euo pipefail + gh api "repos/$GH_REPO/actions/runs/$GITHUB_RUN_ID/artifacts?per_page=100" --jq '.artifacts[].id' | + while read -r artifact_id; do + gh api --method DELETE "repos/$GH_REPO/actions/artifacts/$artifact_id" + done diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..83d6ac5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +.bot/ +artifacts/ +assets/ +inputs/ +out/ +release/ +resolved/ +*.oci.tar +*.oci.tar.sha256 +*.oci.part* +*.published.json +coverage*.xml diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..df22104 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,43 @@ +# Repository instructions + +## Engineering + +- Prioritize correctness, inspect existing code before editing, and preserve compatible working behavior. +- Prefer the smallest safe, reversible change. Match existing naming, structure, and test conventions. +- Prefer PowerShell 7 for orchestration and modern .NET 10 file-based C# applications (`dotnet run --file`) for structured processing and OCI artifact handling. Do not introduce Python dependencies into this repository. +- Maintain `Dockerfile` (`ARG DOCFX_VERSION`) as the single authoritative upstream DocFX CLI version declaration and keep `framework-views/Build-DocfxFrameworkViews.ps1` and `templates/ms-style/framework-views.compat` synchronized with it (`Test-DocfxVersionConsistency`). +- Preserve 100% measured Pester 5 code coverage across `framework-views/*.ps1`, `BuildAndPushDocfxImage.ps1`, `tools/DocfxImage.psm1`, and `tools/Invoke-DocfxRelease.ps1`. +- Validate changes with the relevant executable tests (`./tools/Invoke-UnitTests.ps1`, workflow linting with `actionlint`, and container/framework-view suites as applicable) and report any validation limits honestly. +- Do not push, create tags, create a PR, publish a GitHub release, or publish Docker images without explicit approval. + +## GitHub Actions policy + +- Prefer Codebelt actions and reusable workflows whenever they support the required behavior: + - `codebeltnet/git-checkout@v1` + - `codebeltnet/install-dotnet@v3` (with `versionPrecision: patch`) + - `codebeltnet/oci-artifact-verify@v1` +- Reference actions and reusable workflows with floating major version tags, not commit SHAs. +- Use external actions only where the Codebelt ecosystem has no suitable equivalent. +- Use explicit, fixed runner labels: + - `ubuntu-26.04` (Linux AMD64) + - `ubuntu-26.04-arm` (Linux ARM64) + - `windows-2025` (Windows) +- Never use floating `ubuntu-latest` or `windows-latest` labels. +- Keep least-privilege permissions (`contents: read` at workflow level; elevate only on the specific job that requires `contents: write` / `actions: write` or `actions: read`). +- Never expose Docker Hub credentials to pull request workflows, release preparation jobs, image layers, artifacts, or logs. + +## Delivery lifecycle and versioning + +- Follow the build-once, promote-verified-artifact delivery model across four workflows: + - `.github/workflows/pr.yml` — pull request quality gates (`Required quality gate`), fork-safe without secrets, uploading only lightweight metadata and coverage reports. + - `.github/workflows/container.yml` — reusable native AMD64 (`ubuntu-26.04`) and ARM64 (`ubuntu-26.04-arm`) builder image construction, OCI export with SBOM and SLSA provenance, native runtime validation, and loaded-config verification. + - `.github/workflows/release.yml` — triggered on `vMAJOR.MINOR.PATCH` tags (authoritative Codebelt engine version without leading `v`); runs all quality gates, assembles the exact native-verified AMD64/ARM64 manifests into one multi-platform OCI index without rebuilding, verifies via `tools/OciArtifact.cs` and `codebeltnet/oci-artifact-verify@v1`, splits assets <= 1 GiB, creates a draft GitHub Release, verifies durable asset attachment, and cleans transient Actions artifacts. + - `.github/workflows/deploy.yml` — triggered on GitHub Release `published` (human approval gate) or `workflow_dispatch` from `main` for idempotent recovery; resolves the latest published stable release, validates tag ancestry on `main` and the authoritative `release.yml` run attempt, reconstructs and verifies the exact OCI archive, then promotes it to Docker Hub via Skopeo (`--all --preserve-digests`) under the `Production` environment without rebuilding. +- Engine-qualified tags (`2-v1.1.0`, `2.81-v1.1.0`, `2.81.0-v1.1.0`) are promoted and verified before floating convenience tags (`latest`, `2`, `2.81`, `2.81.0`). Conflicting engine-qualified tags fail closed; identical index digests allow idempotent recovery; superseded releases are blocked from rolling back floating convenience tags. +- Direct `BuildAndPushDocfxImage.ps1 -Publish` targeting `codebeltnet/docfx` or `docker.io/codebeltnet/docfx` is intentionally disabled so official production releases cannot bypass the build-once promotion lifecycle. +- Distinguish repository-implemented workflow automation from manual GitHub administration (the `Production` environment, required reviewers, `DOCKERHUB_USERNAME`/`DOCKERHUB_TOKEN` environment secrets, `main` ruleset required check `Required quality gate`, and Docker Hub selective immutable-tag rules). Never claim administrative settings are configured unless verified. + +## .NET support policy + +- Use only .NET 10 and later SDKs and file-based C# apps (`tools/OciArtifact.cs`, `framework-views/Resolve-DocfxProjects.cs`) for repository tooling. +- Keep builder image SDK and DocFX CLI verification aligned with `Dockerfile` (`ARG DOCFX_VERSION`) and the supported .NET 10/11 SDKs packaged in `Dockerfile`. diff --git a/BuildAndPushDocfxImage.ps1 b/BuildAndPushDocfxImage.ps1 index d704ab6..12db2c7 100644 --- a/BuildAndPushDocfxImage.ps1 +++ b/BuildAndPushDocfxImage.ps1 @@ -1,9 +1,10 @@ #requires -Version 7.0 -[CmdletBinding()] +[CmdletBinding(SupportsShouldProcess)] param( [Parameter(ValueFromPipeline)] - [ValidatePattern('^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$')] - [string] $DocfxVersion = '2.81.0', + [string] $DocfxVersion, + [Parameter(ValueFromPipeline)] + [string] $EngineVersion, [Parameter(ValueFromPipeline)] [string] $DotnetVersion = '10.0', [Parameter(ValueFromPipeline)] @@ -16,61 +17,233 @@ param( [string] $DockerFile = 'Dockerfile', [string] $FrameworkSdkImage, [string] $FrameworkSdkArm64Image, - [switch] $Publish + [string] $SourceRepository = 'https://github.com/codebeltnet/docfx', + [string] $ArchivePath = './artifacts/docfx.oci.tar', + [string] $MetadataFile = './artifacts/docfx-image.json', + [switch] $BuildOnly, + [switch] $RequireNative, + [switch] $SkipContainerTest, + [switch] $Publish, + [switch] $PassThru ) +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' $PSNativeCommandUseErrorActionPreference = $false -function Invoke-Docker([string[]] $Arguments) { - & docker @Arguments - if ($LASTEXITCODE -ne 0) { - throw "docker $($Arguments -join ' ') exited with code $LASTEXITCODE." - } +Import-Module (Join-Path $PSScriptRoot 'tools/DocfxImage.psm1') + +if ($BuildOnly -and $Publish) { + throw 'Cannot combine -BuildOnly and -Publish. Use -BuildOnly for build-once OCI export and validation.' } -$requiredPlatforms = 'linux/arm64', 'linux/amd64' -[string[]] $platforms = if ($Platform) { $Platform.Split(',').Trim() } elseif ($Publish) { $requiredPlatforms } -if ($platforms -and @($platforms -cnotmatch '^linux/(arm64|amd64)(?:/[^/]+)?$').Count) { +$resolvedDocfxInput = if ($PSBoundParameters.ContainsKey('DocfxVersion')) { + $DocfxVersion +} else { + Get-DocfxDefaultVersion -RootPath $PSScriptRoot +} +$cli = Resolve-SemVer $resolvedDocfxInput 'DocfxVersion' + +if (($Publish -or $BuildOnly) -and [string]::IsNullOrWhiteSpace($EngineVersion)) { + $modeName = if ($Publish) { 'Publishing' } else { 'Build-only OCI export' } + throw "$modeName requires an explicit -EngineVersion (for example, -EngineVersion 1.1.0)." +} +$engine = if ($PSBoundParameters.ContainsKey('EngineVersion') -or $EngineVersion) { + Resolve-SemVer $EngineVersion 'EngineVersion' +} + +$requiredPlatforms = @('linux/arm64', 'linux/amd64') +[string[]] $platforms = if ($Platform) { + @($Platform.Split(',') | ForEach-Object { $_.Trim() }) +} elseif ($Publish) { + $requiredPlatforms +} elseif ($BuildOnly) { + @('linux/' + [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant().Replace('x64', 'amd64')) +} else { + [string[]]@() +} + +if (@($platforms).Count -gt 0 -and @($platforms -cnotmatch '^linux/(arm64|amd64)(?:/[^/]+)?$').Count -gt 0) { throw 'Supported builder platforms are linux/amd64 and linux/arm64.' } -$repository = $Tag + +$repository = if ($Publish -or $BuildOnly) { + if ($ContainerRegistry) { "$($ContainerRegistry.TrimEnd('/'))/$Tag" } else { $Tag } +} else { + $Tag +} + if ($Publish) { + if (Test-IsOfficialDocfxRepository -Repository $repository) { + throw "Direct publication to official repository '$repository' is disabled to enforce build-once promotion. Tag a vMAJOR.MINOR.PATCH release to run release.yml and publish the draft GitHub release to trigger deploy.yml." + } foreach ($required in $requiredPlatforms) { if (@($platforms -cmatch "^$required(?:/[^/]+)?$").Count -ne 1) { throw "Specify exactly one platform for '$required' when publishing." } } - if ($ContainerRegistry) { $repository = "$($ContainerRegistry.TrimEnd('/'))/$Tag" } -} elseif ($platforms.Count -gt 1) { - throw 'A local build loads one platform. Specify one platform or omit -Platform to use the builder default.' +} elseif (@($platforms).Count -gt 1) { + throw 'A local or build-only invocation builds one platform at a time. Specify one platform or omit -Platform to use the host default.' +} + +$tagPlan = Resolve-DocfxImageTagPlan -CliVersion $cli -Engine $engine -Repository $repository +$plan = [pscustomobject]@{ + DocfxVersion = $cli.Value + EngineVersion = if ($engine) { $engine.Value } else { $null } + DotnetVersion = $DotnetVersion + Repository = $repository + SourceRepository = $SourceRepository + DockerFile = $DockerFile + Platforms = $platforms + Tags = $tagPlan.AllReferences + ConvenienceTags = $tagPlan.ConvenienceReferences + EngineQualifiedTags = $tagPlan.EngineQualifiedReferences + ArchivePath = [IO.Path]::GetFullPath($ArchivePath) + MetadataFile = [IO.Path]::GetFullPath($MetadataFile) + BuildOnly = [bool]$BuildOnly + Published = $false +} + +$action = if ($Publish) { 'Build and publish Docker image' } elseif ($BuildOnly) { 'Build, export OCI archive, and validate Docker image' } else { 'Build and load local Docker image' } +if (-not $PSCmdlet.ShouldProcess($tagPlan.AllReferences[0], $action)) { + if ($PassThru) { return $plan } + return } -$major, $minor = $DocfxVersion.Split('.')[0..1] -$references = @($DocfxVersion, "$major.$minor", $major, 'latest') | ForEach-Object { "${repository}:$_" } -$buildArguments = @( +$revision = Get-DocfxSourceRevision -Required:($Publish -or $BuildOnly) -RootPath $PSScriptRoot +$labels = Get-DocfxOciLabels -CliVersion $cli -Engine $engine -Revision $revision -SourceRepository $SourceRepository + +$buildArguments = [System.Collections.Generic.List[string]]::new() +$buildArguments.AddRange([string[]]@( 'buildx', 'build', '--file', $DockerFile - '--build-arg', "DOCFX_VERSION=$DocfxVersion" + '--build-arg', "DOCFX_VERSION=$($cli.Value)" '--build-arg', "DOTNET_VERSION=$DotnetVersion" - if ($FrameworkSdkImage) { '--build-arg'; "FRAMEWORK_SDK_IMAGE=$FrameworkSdkImage" } - if ($FrameworkSdkArm64Image) { '--build-arg'; "FRAMEWORK_SDK_ARM64_IMAGE=$FrameworkSdkArm64Image" } - if ($platforms) { '--platform'; ($platforms -join ',') } - foreach ($reference in $references) { '--tag'; $reference } -) +)) +if ($FrameworkSdkImage) { $buildArguments.AddRange([string[]]@('--build-arg', "FRAMEWORK_SDK_IMAGE=$FrameworkSdkImage")) } +if ($FrameworkSdkArm64Image) { $buildArguments.AddRange([string[]]@('--build-arg', "FRAMEWORK_SDK_ARM64_IMAGE=$FrameworkSdkArm64Image")) } +foreach ($labelKey in $labels.Keys) { + $buildArguments.AddRange([string[]]@('--label', "$labelKey=$($labels[$labelKey])")) +} +if (@($platforms).Count -gt 0) { + $buildArguments.AddRange([string[]]@('--platform', ($platforms -join ','))) +} + +if ($BuildOnly) { + $targetPlatform = $platforms[0] + $cpu = ($targetPlatform -split '/')[1] + if ($RequireNative) { + Assert-NativeDockerHost -Platform $targetPlatform + } + $null = Test-SkopeoTransport -if (!$Publish) { - Invoke-Docker ($buildArguments + @('--load', '.')) + $archiveFullPath = [IO.Path]::GetFullPath($ArchivePath) + $metadataFullPath = [IO.Path]::GetFullPath($MetadataFile) + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $archiveFullPath) | Out-Null + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $metadataFullPath) | Out-Null + + $ociArgs = @($buildArguments.ToArray()) + @( + '--output', "type=oci,name=$($tagPlan.AllReferences[0]),dest=$archiveFullPath" + '--sbom=true' + '--provenance=mode=max' + '.' + ) + Invoke-DocfxDocker $ociArgs + + $verified = Invoke-OciArtifact -Arguments @( + 'verify', $archiveFullPath + '--version', $engine.Value + '--docfx-version', $cli.Value + '--revision', $revision + '--source', $SourceRepository + '--platform', $cpu + ) -RootPath $PSScriptRoot | ConvertFrom-Json + + $localImage = "docfx-verify:${cpu}-$([guid]::NewGuid().ToString('N'))" + $loadArchive = Join-Path ([IO.Path]::GetTempPath()) "docfx-load-${cpu}-$([guid]::NewGuid().ToString('N')).docker.tar" + try { + Invoke-Skopeo -Arguments @('copy', '--override-os', 'linux', '--override-arch', $cpu, "oci-archive:$archiveFullPath", "docker-archive:${loadArchive}:${localImage}") + Invoke-DocfxDocker @('load', '--input', $loadArchive) + } finally { + if (Test-Path -LiteralPath $loadArchive) { + Remove-Item -LiteralPath $loadArchive -Force + } + } + + if (-not $SkipContainerTest) { + & (Join-Path $PSScriptRoot 'tests/Test-DocfxContainer.ps1') ` + -Image $localImage ` + -Platform $targetPlatform ` + -DocfxVersion $cli.Value ` + -EngineVersion $engine.Value ` + -Revision $revision ` + -SourceRepository $SourceRepository ` + -RequireNative:$RequireNative + } + + $loadedConfigDigest = (Invoke-OciArtifact -Arguments @( + 'loaded-config', $archiveFullPath + '--platform', $cpu + '--image', $localImage + ) -RootPath $PSScriptRoot).Trim() + + $details = @((Invoke-DocfxDocker @('image', 'inspect', $localImage)) -join "`n" | ConvertFrom-Json)[0] + + foreach ($reference in $tagPlan.AllReferences) { + Invoke-DocfxDocker @('tag', $localImage, $reference) + } + + $record = [pscustomobject]@{ + DocfxVersion = $cli.Value + EngineVersion = $engine.Value + DotnetVersion = $DotnetVersion + Repository = $repository + SourceRepository = $SourceRepository + SourceCommit = $revision + Platform = $targetPlatform + Architecture = $cpu + Tags = $tagPlan.AllReferences + ConvenienceTags = $tagPlan.ConvenienceReferences + EngineQualifiedTags = $tagPlan.EngineQualifiedReferences + ArchivePath = $archiveFullPath + ArchiveSha256 = $verified.archiveSha256 + OciArchiveBytes = (Get-Item -LiteralPath $archiveFullPath).Length + ConfigDigest = $loadedConfigDigest + ImageId = $details.Id + SizeBytes = $details.Size + NativeVerified = (-not $SkipContainerTest) + CreatedUtc = $labels['org.opencontainers.image.created'] + } + $record | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $metadataFullPath -Encoding utf8NoBOM + + if ($PassThru) { return $record } + return +} + +foreach ($reference in $tagPlan.AllReferences) { + $buildArguments.AddRange([string[]]@('--tag', $reference)) +} + +if (-not $Publish) { + Invoke-DocfxDocker ($buildArguments.ToArray() + @('--load', '.')) + if ($PassThru) { return $plan } return } -$metadataFile = New-TemporaryFile +foreach ($reference in $tagPlan.EngineQualifiedReferences) { + Assert-EngineTagAvailableForBuild $reference +} + +$metadataTemp = New-TemporaryFile try { - Invoke-Docker ($buildArguments + @('--push', '--metadata-file', $metadataFile.FullName, '.')) - $digest = (Get-Content -LiteralPath $metadataFile.FullName -Raw | ConvertFrom-Json).'containerimage.digest' - if ($digest -cnotmatch '^sha256:[0-9a-f]{64}$') { throw 'Buildx did not report a valid published image digest.' } + Invoke-DocfxDocker ($buildArguments.ToArray() + @('--push', '--metadata-file', $metadataTemp.FullName, '.')) + $digest = (Get-Content -LiteralPath $metadataTemp.FullName -Raw | ConvertFrom-Json).'containerimage.digest' + if ($digest -cnotmatch '^sha256:[0-9a-f]{64}$') { + throw 'Buildx did not report a valid published image digest.' + } - foreach ($reference in $references) { - $index = Invoke-Docker @('buildx', 'imagetools', 'inspect', '--format', '{{json .Manifest}}', $reference) | + $index = $null + foreach ($reference in $tagPlan.AllReferences) { + $index = Invoke-DocfxDocker @('buildx', 'imagetools', 'inspect', '--format', '{{json .Manifest}}', $reference) | ConvertFrom-Json if ($index.digest -cne $digest -or $index.mediaType -cnotin @( 'application/vnd.oci.image.index.v1+json', 'application/vnd.docker.distribution.manifest.list.v2+json' @@ -78,6 +251,7 @@ try { throw "Published tag '$reference' does not resolve to image index '$digest'." } } + foreach ($required in $requiredPlatforms) { $os, $architecture = $required.Split('/') $manifest = @($index.manifests | Where-Object { @@ -88,14 +262,27 @@ try { if ($manifest.Count -ne 1 -or $manifest[0].digest -cnotmatch '^sha256:[0-9a-f]{64}$') { throw "Published image index '$digest' does not identify one image manifest for '$required'." } - $image = Invoke-Docker @('buildx', 'imagetools', 'inspect', '--format', '{{json .Image}}', "$repository@$($manifest[0].digest)") | + $image = Invoke-DocfxDocker @('buildx', 'imagetools', 'inspect', '--format', '{{json .Image}}', "$repository@$($manifest[0].digest)") | ConvertFrom-Json if ($image.os -cne $os -or $image.architecture -cne $architecture) { throw "Published image config for '$required' reports '$($image.os)/$($image.architecture)'." } + $actualLabels = $image.config.Labels + $expectedLabels = [ordered]@{ + 'org.opencontainers.image.version' = $engine.Value + 'net.codebelt.docfx.engine.version' = $engine.Value + 'net.codebelt.docfx.cli.version' = $cli.Value + 'org.opencontainers.image.revision' = $revision + } + foreach ($labelName in $expectedLabels.Keys) { + $actualValue = if ($actualLabels) { $actualLabels.$labelName } + if ($actualValue -cne $expectedLabels[$labelName]) { + throw "Published image config for '$required' reports label '$labelName' as '$actualValue' instead of '$($expectedLabels[$labelName])'." + } + } } - Write-Output "$($references[0])@$digest" + Write-Output "$($tagPlan.AllReferences[0])@$digest" } finally { - Remove-Item -LiteralPath $metadataFile.FullName + Remove-Item -LiteralPath $metadataTemp.FullName } diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bae90c..f56c69c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,26 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.1.0] - 2026-11-25 + +This is a minor release that introduces native multi-framework views generation, adds framework-aware selection and search routing to the `ms-style` template, introduces engine-aware Docker image versioning with OCI metadata traceability, establishes an automated build-once CI/CD release and deployment lifecycle aligned with `codebeltnet/csrun`, and updates the builder image and tooling for multi-platform .NET 10/11 and PowerShell 7 support. + +### Added + +- Added the native multi-framework views generator (`framework-views/Build-DocfxFrameworkViews.ps1`, `FrameworkViewConventions.ps1`, `DocfxMetadata.ps1`, `Resolve-DocfxProjects.cs`, and `KeepCrossTargetReferences.targets`) with `.docfx/docfx.json` and `.bot/docfx` defaults, `metadata.dest`-derived API roots, MSBuild-evaluated framework precedence, ownership-tracked output reuse, metadata caching, and cross-target project reference recovery, +- Added `framework-views/framework-views.nginx.conf` and `framework-views/framework-views.Dockerfile` to route per-framework API pages, xref maps, and search indexes by `?view=` query parameter in a pinned NGINX site image, +- Added framework-view support to the `ms-style` template (`framework-view.js`, `framework-views.compat`, `_master.tmpl`, and `ms-style.css`) with a TOC framework selector, xref-based view fallback, and view-aware search result URLs, +- Added Codebelt engine-aware Docker image versioning (`-EngineVersion`) with `Dockerfile` (`ARG DOCFX_VERSION`) as the single authoritative upstream DocFX CLI version declaration, producing engine-qualified `-v{EngineVersion}` tags (`2-v1.1.0`, `2.81-v1.1.0`, `2.81.0-v1.1.0`) alongside preserved floating convenience tags (`latest`, `2`, `2.81`, `2.81.0`) on a single multi-platform OCI image index with strict SemVer and Docker tag validation, prerelease isolation, conflict checks, and OCI image metadata labels (`org.opencontainers.image.*`, `net.codebelt.docfx.engine.version`, and `net.codebelt.docfx.cli.version`), +- Added automated GitHub Actions CI/CD workflows aligned with `codebeltnet/csrun` using fixed runners (`ubuntu-26.04`, `ubuntu-26.04-arm`, `windows-2025`), Codebelt actions (`codebeltnet/git-checkout@v1`, `codebeltnet/install-dotnet@v3`, `codebeltnet/oci-artifact-verify@v1`), and workflow linting (`.github/actionlint.yaml`): `.github/workflows/pr.yml` (consolidated `Required quality gate`), `.github/workflows/container.yml` (reusable native AMD64/ARM64 build-once container validation), `.github/workflows/release.yml` (tag-triggered multi-platform OCI assembly, verification, splitting, and draft GitHub Release creation), and `.github/workflows/deploy.yml` (release-publication and manual-recovery promotion to Docker Hub via Skopeo `--all --preserve-digests` without rebuilding, with `Production` environment isolation, concurrency control, idempotent retry, and stale-release protection), +- Added shared PowerShell 7 and `.NET 10` file-based C# delivery tooling (`tools/DocfxImage.psm1`, `tools/OciArtifact.cs`, `tools/Invoke-DocfxRelease.ps1`, `tools/Invoke-UnitTests.ps1`, `tests/Test-DocfxContainer.ps1`), repository guidance (`AGENTS.md`), and `.dockerignore`/`.gitignore` hygiene, +- Added comprehensive automated test suites: `tests/BuildAndPushDocfxImage.Tests.ps1` and `tests/ReleaseDelivery.Tests.ps1` with 100% measured Pester coverage across `BuildAndPushDocfxImage.ps1`, `tools/DocfxImage.psm1`, and `tools/Invoke-DocfxRelease.ps1`, `tests/OciArtifact.Tests.ps1` covering real OCI tar verification, SBOM/provenance checks, multi-platform assembly, and split/reassemble integrity, plus the `tests/framework-view/` unit (100% coverage), synthetic/Cuemon integration, and Playwright browser (`@playwright/test` 1.65.1) suites. + +### Changed + +- Updated `Dockerfile` to base the final builder image on .NET 11 SDK images (`FRAMEWORK_SDK_IMAGE` on `linux/amd64` and `FRAMEWORK_SDK_ARM64_IMAGE` on `linux/arm64`) with PowerShell 7, matching `dotnet-sdk` libc per `TARGETARCH`, `/opt/docfx/framework-views` included, and standard OCI and `net.codebelt.docfx.cli.version` image labels, +- Refactored `BuildAndPushDocfxImage.ps1` onto `tools/DocfxImage.psm1` to share tag planning, version validation, OCI labels, and safeguards between local development and CI, adding `-BuildOnly` (build-once OCI export with SBOM/provenance, verification, Skopeo load, native container testing, and loaded-config digest proof) and `-WhatIf -PassThru` offline planning while blocking direct `-Publish` to official `codebeltnet/docfx` so production releases cannot bypass build-once promotion, +- Updated `README.md`, `framework-views/README.md`, `templates/ms-style/README.md`, and `tests/framework-view/README.md` with CI/CD lifecycle, release/recovery procedures, manual GitHub administrative prerequisites, Docker image versioning contracts, consumer control trade-offs, framework-views setup, and verification instructions. + ## [1.0.1] - 2026-09-27 This is a patch release that upgrades DocFX to 2.81.0. @@ -75,6 +95,7 @@ This is the initial release of the DocFX builder Docker image. - Added a DocFX builder Docker image that includes the default and modern templates, - Added support for running the DocFX build process in a container. +[1.1.0]: https://github.com/codebeltnet/docfx/compare/v1.0.1..v1.1.0 [1.0.1]: https://github.com/codebeltnet/docfx/compare/v1.0.0..v1.0.1 [1.0.0]: https://github.com/codebeltnet/docfx/compare/v0.1.4..v1.0.0 [0.1.4]: https://github.com/codebeltnet/docfx/compare/v0.1.3..v0.1.4 diff --git a/Dockerfile b/Dockerfile index dc82a53..a40086e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -52,4 +52,14 @@ COPY framework-views /opt/docfx/framework-views RUN mkdir -p /build/docfx \ && cp -r /opt/docfx/templates /build/docfx/ +ARG DOCFX_VERSION + +LABEL org.opencontainers.image.title="Codebelt DocFX Builder" \ + org.opencontainers.image.description="Codebelt DocFX builder image with shared templates and native multi-framework views generator." \ + org.opencontainers.image.url="https://github.com/codebeltnet/docfx" \ + org.opencontainers.image.source="https://github.com/codebeltnet/docfx" \ + org.opencontainers.image.vendor="Codebelt" \ + org.opencontainers.image.licenses="MIT" \ + net.codebelt.docfx.cli.version="${DOCFX_VERSION}" + WORKDIR /build diff --git a/README.md b/README.md index 4dfabc2..a6c8988 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ This repository distributes the DocFX builder image, shared templates and native multi-framework documentation generator. -Use [framework views](framework-views/README.md) to generate one native set of API pages, xrefs and search results per target framework. The same PowerShell entry point runs on Windows, Linux, CI and in the builder image. Ordinary DocFX sites continue to use the standard CLI. +Framework views generate one native set of API pages, xrefs and search results per evaluated project target framework. From the consumer repository root, the generator reads `.docfx/docfx.json` and writes to `.bot/docfx`. The same PowerShell entry point runs on Windows, Linux, CI and in the builder image. Ordinary DocFX sites continue to use the standard CLI. [Framework views setup and migration](framework-views/README.md) Consuming repositories only need to provide their DocFX metadata and content with a command such as `ADD [".", "docfx"]` in their documentation Dockerfile. @@ -87,32 +87,161 @@ For the underlying template model, see: - [Custom-template merge guidance](https://dotnet.github.io/docfx/tutorial/howto_create_custom_template.html) - [DocFX template CLI reference](https://dotnet.github.io/docfx/reference/docfx-cli-reference/docfx-template.html) +## Docker image versioning + +The `codebeltnet/docfx` distribution versions two independent dimensions: + +- **DocFX CLI version:** the upstream DocFX CLI and upstream templates packaged in the image (for example, `2.81.0`). +- **Codebelt engine version:** the Semantic Versioning release of `codebeltnet/docfx` itself, covering the `ms-style` template, multi-framework views generator, MSBuild discovery, metadata recovery, and container packaging (for example, `1.1.0`). + +Neither version is inferred from the other. The examples below use DocFX CLI `2.81.0` and Codebelt engine `1.1.0` to illustrate the implemented naming contract; they do not assert that the `1.1.0` tags are publicly available in a registry before release publication occurs. + +### Convenience and engine-qualified tags + +For a standard stable release containing one upstream DocFX CLI version, a single multi-platform build associates all seven tags with the same published image index: + +| Tag family | Image tag | Meaning | +| --- | --- | --- | +| Convenience | `codebeltnet/docfx:latest` | Latest published distribution | +| Convenience | `codebeltnet/docfx:2` | Latest published distribution within DocFX CLI major version `2` | +| Convenience | `codebeltnet/docfx:2.81` | Latest published distribution within DocFX CLI minor version `2.81` | +| Convenience | `codebeltnet/docfx:2.81.0` | Distribution using exact DocFX CLI version `2.81.0` | +| Engine-qualified | `codebeltnet/docfx:2-v1.1.0` | DocFX CLI major version `2` with Codebelt engine `1.1.0` | +| Engine-qualified | `codebeltnet/docfx:2.81-v1.1.0` | DocFX CLI minor version `2.81` with Codebelt engine `1.1.0` | +| Engine-qualified | `codebeltnet/docfx:2.81.0-v1.1.0` | Exact DocFX CLI `2.81.0` with Codebelt engine `1.1.0` | + +Prerelease versions never update floating stable convenience tags: + +- A prerelease Codebelt engine version (for example, `1.2.0-rc.1` with DocFX CLI `2.81.0`) generates only the engine-qualified tags (`2.81.0-v1.2.0-rc.1`, `2.81-v1.2.0-rc.1`, `2-v1.2.0-rc.1`). +- A prerelease DocFX CLI version (for example, `2.82.0-preview.1` with stable Codebelt engine `1.2.0`) generates only the exact CLI tags (`2.82.0-preview.1-v1.2.0` and `2.82.0-preview.1`), or only `2.82.0-preview.1-v1.2.0-rc.1` when both dimensions are prereleases. + +### Consumer control levels + +Existing consumers do not need to migrate; unqualified convenience tags remain supported with their established behavior. Choose the reference level that matches your reproducibility needs: + +- **Convenience** (for example, `codebeltnet/docfx:2` or `codebeltnet/docfx:2.81.0`): automatically receives updated Codebelt engine releases for that DocFX CLI scope. Convenient for low-maintenance builds, but pulling a newer image can introduce breaking Codebelt engine changes independently of the upstream DocFX CLI. +- **Explicit version selection** (for example, `codebeltnet/docfx:2-v1.1.0` or `codebeltnet/docfx:2.81.0-v1.1.0`): selects a specific Codebelt engine release. Published engine-qualified release tags are never intentionally reassigned to different image content during ordinary release operations, and `BuildAndPushDocfxImage.ps1 -Publish` refuses to overwrite existing engine-qualified tags. Because these tags stay fixed to one release, they do not automatically receive future patches or security updates; adopt a newer `-v` release explicitly. +- **Immutable reproducibility** (for example, `codebeltnet/docfx:2.81.0-v1.1.0@sha256:`): Docker tags themselves are mutable pointers by nature. Pinning the published multi-platform image index digest provides content-addressed immutability. + +Client-side preflight checks cannot prevent a race condition against concurrent or external registry writers. Where supported by the destination registry, enable selective registry-enforced immutable-tag rules for engine-qualified tags (for example, Docker Hub immutable-tag pattern `^.+-v[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$`) while keeping convenience tags movable. + +### OCI image metadata + +Every image built with `Dockerfile` and `BuildAndPushDocfxImage.ps1` records both versioning dimensions and source provenance through OCI labels: + +| OCI label | Purpose | +| --- | --- | +| `org.opencontainers.image.version` | Codebelt engine version (`-EngineVersion`, set on published releases and local builds that pass `-EngineVersion`) | +| `net.codebelt.docfx.engine.version` | Explicit Codebelt engine version paired with the CLI version label | +| `net.codebelt.docfx.cli.version` | Upstream DocFX CLI version packaged in the image | +| `org.opencontainers.image.revision` | Git commit SHA of the `codebeltnet/docfx` build source | +| `org.opencontainers.image.created` | RFC 3339 UTC build timestamp | +| `org.opencontainers.image.source` / `org.opencontainers.image.url` | Canonical repository URL (`https://github.com/codebeltnet/docfx`) | +| `org.opencontainers.image.title` / `description` / `vendor` / `licenses` | Distribution identity and MIT license metadata | + ## Build the builder image locally -From the repository root, use PowerShell 7 and Docker Buildx in Linux-container mode. +From the repository root, use PowerShell 7 and Docker Buildx in Linux-container mode. The authoritative upstream DocFX CLI version is declared once in [`Dockerfile`](Dockerfile) (`ARG DOCFX_VERSION=2.81.0`) and validated against `framework-views/Build-DocfxFrameworkViews.ps1` and `templates/ms-style/framework-views.compat`. ```powershell pwsh -NoProfile -File ./BuildAndPushDocfxImage.ps1 -Tag docfx-local ``` -The default loads one platform into Docker and tags it as `docfx-local:2.81.0`, `docfx-local:2.81`, `docfx-local:2`, and `docfx-local:latest`. Supply `-Platform linux/amd64` or `-Platform linux/arm64` to select a platform explicitly. AMD64 uses Alpine and ARM64 uses Ubuntu 26.04, whose .NET 11 SDK includes PowerShell 7 on ARM64. Use the corresponding package manager when extending either image. +Without `-EngineVersion`, the default loads one platform into Docker and tags it with the existing convenience tags (`docfx-local:2.81.0`, `docfx-local:2.81`, `docfx-local:2`, and `docfx-local:latest`). Pass `-EngineVersion` to also generate the engine-qualified tags and set `org.opencontainers.image.version` locally: + +```powershell +pwsh -NoProfile -File ./BuildAndPushDocfxImage.ps1 -Tag docfx-local -EngineVersion 1.1.0 +docker inspect --format '{{json .Config.Labels}}' docfx-local:2.81.0-v1.1.0 +``` + +To plan tags and OCI metadata offline without invoking Docker or Git: -The script accepts `-DocfxVersion` for the CLI and upstream templates and `-DotnetVersion` for the SDK and runtime used by DocFX. The defaults package DocFX 2.81.0 and the .NET 10 and .NET 11 SDKs. Use `-FrameworkSdkImage` or `-FrameworkSdkArm64Image` to override the final SDK base on the corresponding platform. Keep the base's C library compatible with that platform's SDK stage and ensure the base supplies PowerShell 7. The [framework views compatibility contract](framework-views/README.md#template-compatibility) applies when changing the CLI or template. +```powershell +pwsh -NoProfile -File ./BuildAndPushDocfxImage.ps1 -EngineVersion 1.1.0 -BuildOnly -Platform linux/amd64 -WhatIf -PassThru +``` + +To execute the same build-once OCI export, SBOM/provenance verification, Skopeo load, native container test suite (`tests/Test-DocfxContainer.ps1`), and loaded-config digest check used by CI (with no registry writes): + +```powershell +pwsh -NoProfile -File ./BuildAndPushDocfxImage.ps1 -BuildOnly -EngineVersion 1.1.0 -Platform linux/amd64 -RequireNative -PassThru +``` + +`-BuildOnly` requires an OCI-capable Buildx `docker-container` builder (for example, `docker buildx create --driver docker-container --name docfx-builder --use`) and either native `skopeo` or a local Docker daemon (`unix://` / `npipe://`) for the pinned `quay.io/skopeo/stable:v1.20.0` utility container. Add `-SkipContainerTest` during rapid local iteration if you only need the verified OCI archive. + +Supply `-Platform linux/amd64` or `-Platform linux/arm64` to select a platform explicitly. AMD64 uses Alpine and ARM64 uses Ubuntu 26.04, whose .NET 11 SDK includes PowerShell 7 on ARM64. Use the corresponding package manager when extending either image. -## Publish and verify the builder image +The script accepts `-DocfxVersion` (defaulting to `ARG DOCFX_VERSION` in `Dockerfile`), `-EngineVersion` for the Codebelt engine Semantic Version (without a leading `v` or `+` build metadata), and `-DotnetVersion` for the SDK and runtime used by DocFX. The defaults package DocFX `2.81.0` and the .NET 10 and .NET 11 SDKs. Use `-FrameworkSdkImage` or `-FrameworkSdkArm64Image` to override the final SDK base on the corresponding platform. Keep the base's C library compatible with that platform's SDK stage and ensure the base supplies PowerShell 7. The [framework views compatibility contract](framework-views/README.md#template-compatibility) applies when changing the CLI or template. -For an authorized release, select a Buildx builder that can build `linux/amd64` and `linux/arm64`, using native nodes or emulation. Use `docker buildx inspect --bootstrap` to check the builder's platforms. If needed, create a builder with `docker buildx create --driver docker-container --name docfx-release --use`. Sign in to the destination registry and run the publishing script from the repository root. +To run all PowerShell unit test suites with 100% enforced coverage (covering `framework-views/*.ps1`, `BuildAndPushDocfxImage.ps1`, `tools/DocfxImage.psm1`, and `tools/Invoke-DocfxRelease.ps1`) plus the `.NET 10` OCI artifact test suite (`tests/OciArtifact.Tests.ps1`): ```powershell -pwsh -NoProfile -File ./BuildAndPushDocfxImage.ps1 -Publish +pwsh -NoProfile -File ./tools/Invoke-UnitTests.ps1 +``` + +## CI/CD release and deployment lifecycle + +Official `codebeltnet/docfx` releases follow a build-once, promote-verified-artifact delivery lifecycle aligned with `codebeltnet/csrun`: + +```text +Pull request (.github/workflows/pr.yml) + -> Required quality gate (unit tests + 100% coverage, native Windows/Linux, browser/routing, Cuemon, native AMD64 & ARM64 containers, workflow lint) + -> Merge to main + -> Push vMAJOR.MINOR.PATCH Git release tag (.github/workflows/release.yml) + -> Run full quality gates & native AMD64/ARM64 OCI builds (.github/workflows/container.yml) + -> Assemble multi-platform OCI index without rebuilding & verify via OciArtifact.cs + codebeltnet/oci-artifact-verify@v1 + -> Create draft GitHub Release with durable split OCI assets & checksums, then clean transient CI artifacts + -> Human approves and publishes the GitHub Release (.github/workflows/deploy.yml) + -> Reconstruct & re-verify durable OCI assets, then promote to Docker Hub via Skopeo (--all --preserve-digests) + -> Verify all seven tags resolve to the exact multi-platform OCI index digest & re-verify downloaded registry content ``` -Existing release callers must add `-Publish`. The script sends one multi-platform build directly to the registry under the exact, major/minor, major, and `latest` tags. It verifies that all four tags resolve to the built index digest and fetches both required image configs to verify their platforms. On success it prints `codebeltnet/docfx:2.81.0@sha256:`. Use `-ContainerRegistry` and `-Tag` for a different registry namespace or repository. +### Workflow segregation + +| Workflow | Trigger | Purpose & permissions | +| --- | --- | --- | +| [`.github/workflows/pr.yml`](.github/workflows/pr.yml) | `pull_request` to `main`, `workflow_dispatch` | Runs workflow syntax linting (`actionlint`), `Dockerfile` `ARG DOCFX_VERSION` consistency checks, PowerShell unit tests with 100% coverage + `.NET 10` OCI tests (`ubuntu-26.04` & `windows-2025`), native framework-views regression (`ubuntu-26.04` with NGINX routing & `windows-2025`), Playwright browser & HTTP routing tests, pinned Cuemon acceptance tests, and native AMD64/ARM64 container validation via `container.yml`. Consolidated under **Required quality gate**. Strictly `contents: read`, fork-safe, zero secrets, no large OCI archive uploads. | +| [`.github/workflows/container.yml`](.github/workflows/container.yml) | Reusable (`workflow_call`) | Invoked by both `pr.yml` and `release.yml`. Builds the candidate image once natively on `ubuntu-26.04` (`linux/amd64`) and `ubuntu-26.04-arm` (`linux/arm64`) with SBOM and maximum SLSA provenance, verifies the exported OCI archive, loads it via Skopeo, executes `tests/Test-DocfxContainer.ps1` on native CPU, and verifies `loaded-config` byte equality. Uploads full OCI archives only on tagged release pushes (1-day retention); PR runs upload small JSON metadata only. | +| [`.github/workflows/release.yml`](.github/workflows/release.yml) | Push of `v*` tag | Validates strict `vMAJOR.MINOR.PATCH` release tag (authoritative Codebelt engine version without `v`), executes all quality gates and `container.yml`, assembles the exact tested AMD64 & ARM64 manifests into a single multi-platform OCI image index without rebuilding, verifies integrity with `tools/OciArtifact.cs` and `codebeltnet/oci-artifact-verify@v1`, splits assets <= 1 GiB (`docfx.oci.part000`, ...), creates a **draft GitHub Release** with `docfx-release.json` and `docfx.oci.tar.sha256`, verifies durable release asset attachment, and removes transient workflow artifacts. Never touches Docker Hub. | +| [`.github/workflows/deploy.yml`](.github/workflows/deploy.yml) | GitHub Release `published`, `workflow_dispatch` | Resolves the approved latest published stable release from `main` (checking tag ancestry on `main` and rejecting drafts, prereleases, or superseded releases), reconstructs and verifies the durable OCI release assets (authoritative `release.yml` run attempt, both native results, checksums, attestations, and `codebeltnet/oci-artifact-verify@v1`), then promotes under the `Production` environment using Skopeo (`--all --preserve-digests`) without rebuilding. Serialized by concurrency group `docfx-production`. | + +### Authoritative versioning and promotion safeguards + +- **Release tag convention:** Git tags use `vMAJOR.MINOR.PATCH` (for example, `v1.1.0`), which defines Codebelt engine version `1.1.0`. The upstream DocFX CLI version (`2.81.0`) is maintained independently in `Dockerfile` (`ARG DOCFX_VERSION`). +- **Single implementation:** Local builds (`BuildAndPushDocfxImage.ps1`), CI container validation, release assembly, and deployment promotion all share [`tools/DocfxImage.psm1`](tools/DocfxImage.psm1) and [`tools/OciArtifact.cs`](tools/OciArtifact.cs) (a `.NET 10` file-based C# application). +- **Direct-publish safeguard:** `BuildAndPushDocfxImage.ps1 -Publish` intentionally refuses direct `docker buildx build --push` against the official `codebeltnet/docfx` (or `docker.io/codebeltnet/docfx`) repository so production releases cannot bypass build-once native verification and release approval. Custom or fork registries (for example, `-ContainerRegistry localhost:5000/team/`) remain supported for local/fork workflows. +- **Two-phase promotion & conflict protection:** `deploy.yml` preflights all engine-qualified tags (`2.81.0-v1.1.0`, `2.81-v1.1.0`, `2-v1.1.0`) before any registry write. Missing tags are uploaded; tags already pointing to the exact expected OCI index digest are accepted for idempotent retry; any tag pointing to different content fails closed without overwriting. Floating convenience tags (`2.81.0`, `2.81`, `2`, `latest`) are updated only after all engine-qualified tags exist in the registry with the exact expected digest and after re-confirming the release is still the latest published stable release. +- **Post-publish verification:** After promotion, `deploy.yml` inspects every promoted tag's raw manifest digest to prove no manifest rewriting occurred, then downloads the image by immutable digest (`codebeltnet/docfx@sha256:`) and re-verifies all blobs, both platforms, OCI labels, SPDX SBOM, and SLSA provenance. + +### Deployment recovery procedure + +To resume or recover a partially completed production deployment of the latest published release: + +1. Never rebuild the image or re-tag a release for recovery. +2. In GitHub Actions, manually dispatch **Deploy Docker Hub images** (`.github/workflows/deploy.yml`) from branch `main` with `tag` set to the already-published latest release tag (for example, `v1.1.0`). +3. `deploy.yml` loads deployment tooling from `main` (pinned to a single `deployment-sha`), downloads the original durable OCI assets from the GitHub Release, re-verifies checksums, the authoritative `release.yml` run, native results, and OCI attestations, skips any engine-qualified tag already matching the exact expected index digest, and completes the remaining promotions idempotently. +4. Attempting to dispatch recovery from a non-`main` branch, for a draft/prerelease, or for an older superseded release is automatically rejected to prevent rolling back floating convenience tags (`latest`, `2`, `2.81`, `2.81.0`). + +### Manual GitHub & Docker Hub administrative configuration + +Adding workflow YAML files to this repository does **not** automatically configure GitHub environments, secrets, repository rulesets, or Docker Hub policies. Repository administrators must configure the following settings manually before running production deployments: + +1. **GitHub Environment (`Production`):** + - Create an environment named `Production` in `codebeltnet/docfx` (**Settings -> Environments**). + - Configure required reviewers and restrict deployment branches/tags appropriately. + - Add the following **environment secrets** (never repository-wide secrets exposed to PRs): + - `DOCKERHUB_USERNAME` — Docker Hub account username. + - `DOCKERHUB_TOKEN` — Docker Hub access token scoped strictly to `codebeltnet/docfx`. +2. **Branch Ruleset (`main`):** + - Update the active `main` branch ruleset to require the consolidated status check **`Required quality gate`** from `.github/workflows/pr.yml`. +3. **Docker Hub Selective Immutable Tags (recommended):** + - Enable selective immutable-tag rules on `codebeltnet/docfx` for engine-qualified tags using pattern `^.+-v[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$` while keeping floating convenience tags movable. + +### Inspecting a published release -Inspect the exact tag to retrieve the digest and platform list after release. +After a release has been promoted to Docker Hub, inspect any published engine-qualified tag to retrieve the multi-platform image index digest: ```powershell -docker buildx imagetools inspect codebeltnet/docfx:2.81.0 +docker buildx imagetools inspect codebeltnet/docfx:2.81.0-v1.1.0 ``` -Use the top-level `Digest` field in `codebeltnet/docfx:2.81.0@sha256:`. Record the digest from the approved release alongside the source commit. The version tags can move, including the exact CLI tag when builder content changes. See [Run in the builder image](framework-views/README.md#run-in-the-builder-image) for the consumer command. +Use the top-level `Digest` field in `codebeltnet/docfx:2.81.0-v1.1.0@sha256:` for content-addressed immutability. See [Run in the builder image](framework-views/README.md#run-in-the-builder-image) for the consumer command. diff --git a/framework-views/Build-DocfxFrameworkViews.ps1 b/framework-views/Build-DocfxFrameworkViews.ps1 index 3fccb43..70be7c0 100644 --- a/framework-views/Build-DocfxFrameworkViews.ps1 +++ b/framework-views/Build-DocfxFrameworkViews.ps1 @@ -1,9 +1,8 @@ #requires -Version 7.0 [CmdletBinding()] param( - [Parameter(Mandatory)][string] $DocfxConfig, - [Parameter(Mandatory)][string] $SettingsPath, - [Parameter(Mandatory)][string] $OutputRoot, + [string] $DocfxConfig = '.docfx/docfx.json', + [string] $OutputRoot = '.bot/docfx', [switch] $NoRestore, [switch] $ForceMetadata, [string] $MetadataCache, @@ -12,78 +11,45 @@ param( $ErrorActionPreference = 'Stop' $PSNativeCommandUseErrorActionPreference = $false +. "$PSScriptRoot/FrameworkViewConventions.ps1" +. "$PSScriptRoot/DocfxMetadata.ps1" -function Invoke-Step([string] $Log, [string] $Command, [string[]] $Arguments) { +function Invoke-Step([string] $Log, [string] $Command, [string[]] $Arguments, [switch] $ReturnExitCode) { & $Command @Arguments *> $Log + if ($ReturnExitCode) { return $LASTEXITCODE } if ($LASTEXITCODE -ne 0) { Get-Content -LiteralPath $Log -Tail 25 | Write-Host throw "$Command exited with $LASTEXITCODE. See $Log" } } -function Write-Json([string] $Path, $Value) { - ConvertTo-Json -InputObject $Value -Depth 100 | Set-Content -LiteralPath $Path -} - -function Read-Json([string] $Path) { - Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json -AsHashtable -NoEnumerate -} - -function Get-MetadataFingerprint([string[]] $Directories) { - $entries = foreach ($directory in $Directories) { - if (!(Test-Path -LiteralPath "$directory/.manifest" -PathType Leaf)) { return } - foreach ($file in Get-ChildItem -LiteralPath $directory -Recurse -File -Force | Where-Object { $_.Extension -eq '.yml' -or $_.Name -eq '.manifest' } | Sort-Object FullName -CaseSensitive) { - "$([IO.Path]::GetRelativePath($directory, $file.FullName).Replace('\', '/'))=$((Get-FileHash -LiteralPath $file.FullName).Hash)" - } - } - [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes(($entries -join "`n")))) -} - $configPath = (Resolve-Path -LiteralPath $DocfxConfig).Path $source = Split-Path -Parent $configPath -$settingsFile = (Resolve-Path -LiteralPath $SettingsPath).Path -$settings = Read-Json $settingsFile -$apiPath = $settings.apiPath -$defaultFramework = $settings.defaultFramework -$framework = $settings.frameworks -$alignAssemblyVersion = $settings.alignAssemblyVersion -eq $true -$builderImage = $settings.builderImage -$sharedTemplatePath = if ($settings.templatePath) { - [IO.Path]::GetFullPath($settings.templatePath, (Split-Path -Parent $settingsFile)) -} elseif (!$builderImage) { - "$PSScriptRoot/../templates/ms-style" -} -if (!$defaultFramework) { throw "Specify defaultFramework in '$settingsFile'." } $work = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputRoot) -$relativeWork = [IO.Path]::GetRelativePath($source, $work) -if ($relativeWork -eq '.' -or ($relativeWork -ne '..' -and !$relativeWork.StartsWith("..$([IO.Path]::DirectorySeparatorChar)") -and ![IO.Path]::IsPathRooted($relativeWork))) { - throw 'Place the framework output outside the DocFX input directory.' -} -if ((Test-Path -LiteralPath $work) -and @(Get-ChildItem -LiteralPath $work -Force).Count) { - throw "Framework output directory must be empty: $work" +if ((Test-PathWithin $source $work) -or (Test-PathWithin $work $source) -or + (Test-PathWithin $work (Get-Location).ProviderPath) -or (Test-PathWithin $work $PSScriptRoot)) { + throw 'Place the framework output in a dedicated directory outside the DocFX input directory.' } -if ($ApiPath -cnotmatch '^[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*$') { throw "Invalid API path: $ApiPath" } +Assert-SafeOutputPath $work if ($MetadataCache -and !$MetadataCacheKey) { throw 'A metadata cache requires a metadata input fingerprint.' } -if ($MetadataCache) { $MetadataCache = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($MetadataCache) } -if ($SharedTemplatePath) { $SharedTemplatePath = (Resolve-Path -LiteralPath $SharedTemplatePath).Path } -New-Item -ItemType Directory -Path $work -Force | Out-Null -Write-Host "Artifacts: $work" +if ($MetadataCache) { + $MetadataCache = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($MetadataCache) + if ((Test-PathWithin $work $MetadataCache) -or (Test-PathWithin $MetadataCache $work) -or + (Test-PathWithin $source $MetadataCache) -or (Test-PathWithin $MetadataCache $source)) { + throw 'Use a dedicated metadata cache directory outside the DocFX inputs and framework output.' + } + Assert-SafeOutputPath $MetadataCache +} $config = Read-Json $configPath -$buildDestination = if ($config.build.dest) { $config.build.dest } elseif ($config.build.output) { $config.build.output } else { '_site' } +$apiPath = Get-ApiPath $config['metadata'] +$buildSettings = $config['build'] ?? @{} +$buildDestination = if ($buildSettings['dest']) { $buildSettings['dest'] } elseif ($buildSettings['output']) { $buildSettings['output'] } else { '_site' } if ($buildDestination -cnotmatch '^[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*$' -or $buildDestination -match '(^|/)\.{1,2}(/|$)') { throw 'Framework views require a relative DocFX site destination.' } -if (!$config.metadata.Count) { throw 'Configure at least one project metadata group.' } -foreach ($group in $config.metadata) { - if ($group.dest -cnotmatch '^[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*$' -or - ($group.dest -cne $ApiPath -and !$group.dest.StartsWith("$ApiPath/", [StringComparison]::Ordinal))) { - throw "Metadata destination '$($group.dest)' must be at or below '$ApiPath'." - } -} - $supportedDocfx = '2.81.0' -$docfx = (Get-Command docfx -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1).Source +$docfx = Get-Command docfx -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Source if (!$docfx) { throw "Install DocFX $supportedDocfx as a .NET tool and add its executable to PATH." } $version = & $docfx --version if ($LASTEXITCODE -ne 0 -or !$version) { throw 'Could not determine the installed DocFX version.' } @@ -92,24 +58,20 @@ if (($version -split '\+', 2)[0] -cne $supportedDocfx) { throw "Framework views use DocFX $supportedDocfx for project discovery. Install that CLI version (found '$version')." } -$shared = "$work/shared" -New-Item -ItemType Directory -Path $shared | Out-Null -if ($builderImage) { - Invoke-Step "$work/builder-version.log" docker @('run', '--rm', $builderImage, 'docfx', '--version') - $builderVersion = (Get-Content -LiteralPath "$work/builder-version.log" -Raw).Trim() - if (($builderVersion -split '\+', 2)[0] -cne $supportedDocfx) { - throw "Framework views use DocFX $supportedDocfx for rendering. The builder image reports '$builderVersion'." +$frameworkTemplate = @($buildSettings['template'] | Where-Object { $_ -and (Split-Path -Leaf $_) -ceq 'ms-style' }) +if ($frameworkTemplate.Count -ne 1) { throw 'Configure one ms-style entry in the DocFX build template list.' } +$templateSource = [IO.Path]::GetFullPath($frameworkTemplate[0], $source) +if (!(Test-Path -LiteralPath $templateSource)) { + if ($templateSource -cnotin @([IO.Path]::GetFullPath('templates/ms-style', $source), [IO.Path]::GetFullPath('ms-style', $source))) { + throw "The ms-style template configured in docfx.json was not found at '$templateSource'." } + $templateSource = [IO.Path]::GetFullPath("$PSScriptRoot/../templates/ms-style") } -if ($sharedTemplatePath) { - Copy-Item -LiteralPath $sharedTemplatePath -Destination "$shared/ms-style" -Recurse -} else { - Invoke-Step "$work/templates.log" docker @('run', '--rm', '--mount', "type=bind,source=$shared,target=/stage", - $builderImage, 'cp', '-R', '/opt/docfx/templates/ms-style', '/stage/ms-style') +if ((Test-PathWithin $templateSource $work) -or (Test-PathWithin $work $templateSource)) { + throw 'Place the framework output outside the ms-style template directory.' } -$templateSource = if ($sharedTemplatePath) { $sharedTemplatePath } else { "$builderImage (/opt/docfx/templates/ms-style)" } $expectedContract = "framework-views-v1/docfx-$supportedDocfx" -$marker = "$shared/ms-style/framework-views.compat" +$marker = "$templateSource/framework-views.compat" $templateContract = if (Test-Path -LiteralPath $marker -PathType Leaf) { [IO.File]::ReadAllText($marker).Trim() } @@ -117,7 +79,7 @@ if ($templateContract -cne $expectedContract) { $actualContract = if ($templateContract) { "'$templateContract'" } else { 'missing or empty' } throw "Incompatible ms-style template at '$templateSource'. Expected '$expectedContract' in framework-views.compat, found $actualContract." } -if (!(Test-Path -LiteralPath "$shared/ms-style/public/framework-view.js" -PathType Leaf)) { +if (!(Test-Path -LiteralPath "$templateSource/public/framework-view.js" -PathType Leaf)) { throw "Incompatible ms-style template at '$templateSource'. Missing public/framework-view.js." } @@ -130,260 +92,219 @@ $tools = Get-ChildItem -LiteralPath $store -Filter Docfx.Glob.dll -File -Recurse } | Select-Object -First 1 if (!$tools) { throw "Install DocFX as a .NET tool so its mapping library can be found in $store." } $resolver = "$PSScriptRoot/Resolve-DocfxProjects.cs" -$resolvedPath = "$work/projects.json" -$resolverDirectory = "$work/resolver" -New-Item -ItemType Directory -Path $resolverDirectory | Out-Null -# The file-based app needs .NET 10 or later even if the project pins an older SDK. -Write-Json "$resolverDirectory/global.json" @{ sdk = @{ version = '10.0.100'; rollForward = 'latestMajor'; allowPrerelease = $true } } -# File-based builds cache their intermediates by source path. Give each invocation its own. -$stagedResolver = Join-Path $resolverDirectory 'Resolve-DocfxProjects.cs' -Copy-Item -LiteralPath $resolver -Destination $stagedResolver -Push-Location $resolverDirectory -try { - Invoke-Step "$work/resolver-sdk.log" dotnet @('--version') - $resolverSdk = (Get-Content -LiteralPath "$work/resolver-sdk.log" -Raw).Trim() - # OutputRoot may be under the consumer checkout. Apply its MSBuild configuration only to its projects. - Invoke-Step "$work/discovery.log" dotnet @('run', '--file', $stagedResolver, - '-p:ImportDirectoryBuildProps=false', '-p:ImportDirectoryBuildTargets=false', '-p:ImportDirectoryPackagesProps=false', - '--', $tools.DirectoryName, $configPath, $resolvedPath) -} finally { - Pop-Location +$crossTargetReferences = "$PSScriptRoot/KeepCrossTargetReferences.targets" +$ownershipFile = '.docfx-framework-views' +$lockFile = '.docfx-framework-views.lock' +New-Item -ItemType Directory -Path $work -Force | Out-Null +$lockPath = "$work/$lockFile" +$lockItem = Get-Item -LiteralPath $lockPath -Force -ErrorAction SilentlyContinue +if ($lockItem -and ($lockItem.PSIsContainer -or ($lockItem.Attributes -band [IO.FileAttributes]::ReparsePoint))) { + throw "Invalid framework output lock at '$lockPath'." } -Push-Location $source +if (!$lockItem) { $null = Get-FrameworkOutputEntries $work $ownershipFile $lockFile } +$outputLock = [IO.File]::Open($lockPath, 'OpenOrCreate', 'ReadWrite', 'None') try { - $mappings = Read-Json $resolvedPath - $projects = [Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal) - $groups = for ($groupIndex = 0; $groupIndex -lt $config.metadata.Count; $groupIndex++) { - $group = $config.metadata[$groupIndex] - if (!$group.properties) { $group.properties = @{} } - $groupProjects = @( - foreach ($mapping in $mappings[$groupIndex]) { - $root = if ($mapping.source) { [IO.Path]::GetFullPath($mapping.source, $source) } else { $source } - foreach ($file in $mapping.files) { - if ([IO.Path]::GetExtension($file) -notin '.csproj', '.fsproj', '.vbproj') { - throw "Framework views require project inputs. Found '$file' in '$($group.dest)'." - } - $path = [IO.Path]::GetFullPath($file) - $relative = [IO.Path]::GetRelativePath($root, $path).Replace('\', '/') - $properties = @($group.properties.GetEnumerator() | ForEach-Object { "-p:$($_.Key)=$($_.Value)" }) - if ($group.properties.Contains('TargetFramework')) { throw "Remove TargetFramework from the properties for '$($group.dest)'." } - if (!$projects.ContainsKey($path)) { - $evaluation = & dotnet msbuild $path -nologo -getProperty:TargetFrameworks,TargetFramework @properties - if ($LASTEXITCODE -ne 0) { throw "MSBuild evaluation failed for $path." } - # SDK first-run messages and project warnings can precede the property JSON. - $evaluationText = $evaluation -join "`n" - $propertyJson = [regex]::Match($evaluationText, '(?ms)^\{\n.*?^\}$') - if (!$propertyJson.Success) { throw "MSBuild did not return target framework properties for ${path}: $evaluationText" } - $evaluated = ($propertyJson.Value | ConvertFrom-Json).Properties - $targets = @("$($evaluated.TargetFrameworks);$($evaluated.TargetFramework)" -split ';' | Where-Object { $_ } | Select-Object -Unique) - if (!$targets.Count) { throw "No target frameworks for $path." } - $projects[$path] = @{ targets = $targets; properties = $properties; id = $projects.Count } - Write-Host "$relative declares $($targets -join ', ')" - } elseif (($projects[$path].properties -join "`n") -cne ($properties -join "`n")) { - throw "Use the same metadata properties for each occurrence of '$path'." + $previousOutput = @(Get-FrameworkOutputEntries $work $ownershipFile $lockFile) + foreach ($entry in $previousOutput) { Remove-Item -LiteralPath $entry.FullName -Recurse -Force } + Set-Content -LiteralPath "$work/$ownershipFile" -Value @('docfx-framework-views-v1', 'resolver', 'projects.json', 'resolver-sdk.log', 'discovery.log') + Write-Host "Artifacts: $work" + $resolvedPath = "$work/projects.json" + $resolverDirectory = "$work/resolver" + New-Item -ItemType Directory -Path $resolverDirectory | Out-Null + # The file-based app needs .NET 10 or later even if the project pins an older SDK. + Write-Json "$resolverDirectory/global.json" @{ sdk = @{ version = '10.0.100'; rollForward = 'latestMajor'; allowPrerelease = $true } } + # File-based builds cache their intermediates by source path. Give each invocation its own. + $stagedResolver = Join-Path $resolverDirectory 'Resolve-DocfxProjects.cs' + Copy-Item -LiteralPath $resolver -Destination $stagedResolver + Push-Location $resolverDirectory + try { + Invoke-Step "$work/resolver-sdk.log" dotnet @('--version') + $resolverSdk = (Get-Content -LiteralPath "$work/resolver-sdk.log" -Raw).Trim() + # OutputRoot may be under the consumer checkout. Apply its MSBuild configuration only to its projects. + Invoke-Step "$work/discovery.log" dotnet @('run', '--file', $stagedResolver, + '-p:ImportDirectoryBuildProps=false', '-p:ImportDirectoryBuildTargets=false', '-p:ImportDirectoryPackagesProps=false', + '--', $tools.DirectoryName, $configPath, $resolvedPath) + } finally { + Pop-Location + } + Push-Location $source + try { + $mappings = Read-Json $resolvedPath + $projects = [Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal) + $groups = for ($groupIndex = 0; $groupIndex -lt $config.metadata.Count; $groupIndex++) { + $group = $config.metadata[$groupIndex] + if (!$group['properties']) { $group['properties'] = @{} } + if (!$group.properties.Contains('Configuration')) { $group.properties.Configuration = 'Release' } + $groupProjects = @( + foreach ($mapping in $mappings[$groupIndex]) { + $root = if ($mapping['source']) { [IO.Path]::GetFullPath($mapping['source'], $source) } else { $source } + foreach ($file in $mapping.files) { + if ([IO.Path]::GetExtension($file) -notin '.csproj', '.fsproj', '.vbproj') { + throw "Framework views require project inputs. Found '$file' in '$($group.dest)'." + } + $path = [IO.Path]::GetFullPath($file) + if (Test-PathWithin $work $path) { throw "Project '$path' is inside the framework output. Move the project or output directory." } + $relative = [IO.Path]::GetRelativePath($root, $path).Replace('\', '/') + $properties = @($group.properties.GetEnumerator() | ForEach-Object { "-p:$($_.Key)=$($_.Value)" }) + if ($group.properties.Contains('TargetFramework')) { throw "Remove TargetFramework from the properties for '$($group.dest)'." } + if (!$projects.ContainsKey($path)) { + $evaluation = & dotnet msbuild $path -nologo -getProperty:TargetFrameworks,TargetFramework @properties + if ($LASTEXITCODE -ne 0) { throw "MSBuild evaluation failed for $path." } + $evaluated = (Read-MSBuildJson $evaluation $path).Properties + $evaluatedTargets = if ($evaluated.TargetFramework) { $evaluated.TargetFramework } else { $evaluated.TargetFrameworks } + $targets = @($evaluatedTargets -split ';' | ForEach-Object Trim | Where-Object { $_ } | Select-Object -Unique) + if (!$targets.Count) { throw "No target frameworks for $path." } + $discovered = @(foreach ($target in $targets) { Get-FrameworkView $target $path }) + $projects[$path] = @{ targets = $targets; frameworks = $discovered; properties = $properties; id = $projects.Count } + Write-Host "$relative declares $($targets -join ', ')" + } elseif (($projects[$path].properties -join "`n") -cne ($properties -join "`n")) { + throw "Use the same metadata properties for each occurrence of '$path'." + } + @{ path = $path; root = $root; relative = $relative } } - @{ path = $path; root = $root; relative = $relative } } - } - ) - if (!$groupProjects.Count) { throw "No project matched metadata destination '$($group.dest)'." } - @{ config = $group; projects = $groupProjects } - } - - $matrix = @($projects.Values | ForEach-Object { $_.targets } | Sort-Object -Unique -CaseSensitive) - if (!$Framework) { - # Prefer the configured default, then follow the target order declared by the projects. - $Framework = @($DefaultFramework; foreach ($group in $groups) { - foreach ($project in $group.projects) { $projects[$project.path].targets } - }) | Select-Object -Unique - } - if ($DefaultFramework -cnotin $Framework -or @($Framework | Select-Object -Unique).Count -ne $Framework.Count) { - throw 'The ordered framework list must include the default and contain unique targets.' - } - $views = [ordered]@{} - foreach ($tfm in $Framework) { - if ($tfm -cnotin $matrix) { throw "Undeclared framework: $tfm" } - if ($tfm -cnotmatch '^(net|netstandard|netcoreapp)(\d+)\.(\d+)$' -and $tfm -cnotmatch '^(net)([1-4])([0-9]+)$') { - throw "No public view mapping for $tfm." + ) + if (!$groupProjects.Count) { throw "No project matched metadata destination '$($group.dest)'." } + @{ config = $group; projects = $groupProjects } } - $view = if ($tfm.Contains('.')) { "$($Matches[1])-$($Matches[2]).$($Matches[3])" } else { $tfm } - $directory = if ($tfm -cmatch '^net([5-9]|[1-9]\d+)\.0$') { "net$($Matches[1])" } else { $tfm } - $views[$view] = [ordered]@{ tfm = $tfm; directory = $directory; xref = "/xrefmap.yml?view=$view"; projects = @() } - } - $sdk = (& dotnet --version).Trim() - if ($LASTEXITCODE -ne 0) { throw 'Could not determine the selected .NET SDK.' } - if ($MetadataCache) { - $cacheVersion = @(Get-FileHash -LiteralPath $PSCommandPath, $resolver, $configPath, $resolvedPath | ForEach-Object Hash) -join ':' - $cacheInputs = "$version/$sdk/$resolverSdk/$cacheVersion/$MetadataCacheKey/$DefaultFramework/$($Framework -join ',')/$AlignAssemblyVersion" - $cacheId = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($cacheInputs))) - $cacheRoot = "$MetadataCache/$cacheId" - New-Item -ItemType Directory -Path $cacheRoot -Force | Out-Null - } - $restored = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) - foreach ($view in $views.Keys) { - $entry = $views[$view] - $tfm = $entry.tfm - $mixedTargets = $AlignAssemblyVersion -and @($projects.Values | Where-Object { $tfm -cnotin $_.targets }).Count -gt 0 - $stage = "$work/$($entry.directory)" - New-Item -ItemType Directory -Path $stage | Out-Null - foreach ($item in Get-ChildItem -LiteralPath $source -Force) { - if ($item.Name -in @('.git', 'bin', 'obj', 'wwwroot', '_site', ($buildDestination -split '/')[0])) { continue } - Copy-Item -LiteralPath $item.FullName -Destination $stage -Recurse -Force + $views = [ordered]@{} + foreach ($framework in Get-OrderedFrameworkViews ($projects.Values | ForEach-Object { $_.frameworks })) { + $view = $framework.view + $views[$view] = [ordered]@{ tfm = $framework.tfm; directory = $framework.directory; xref = "/xrefmap.yml?view=$view"; projects = @() } } - $metadata = @( - foreach ($group in $groups) { - $original = $group.config - $destination = "$stage/$($original.dest)" - if (Test-Path -LiteralPath $destination -PathType Container) { - Get-ChildItem -LiteralPath $destination -Recurse -File -Force | Where-Object { - $_.Name -eq '.manifest' -or ($_.Extension -eq '.yml' -and (Get-Content -LiteralPath $_.FullName -TotalCount 1) -match '^### YamlMime:(ManagedReference|ApiPage|TableOfContent)') - } | Remove-Item -Force - # Native metadata TOCs have no YAML MIME marker. - $originManifest = Join-Path $source "$($original.dest)/.manifest" - if (Test-Path -LiteralPath $originManifest -PathType Leaf) { - $generatedToc = Join-Path $destination 'toc.yml' - if (Test-Path -LiteralPath $generatedToc -PathType Leaf) { Remove-Item -LiteralPath $generatedToc } - } - } - $selected = @($group.projects | Where-Object { $tfm -cin $projects[$_.path].targets }) - if (!$selected.Count) { continue } - $entry.projects += @($selected.relative) - $metadataGroup = ConvertTo-Json $original -Depth 100 | ConvertFrom-Json -AsHashtable - $metadataGroup.src = @($selected | Group-Object root | ForEach-Object { @{ src = $_.Name; files = @($_.Group.relative) } }) - $metadataGroup.properties.TargetFramework = $tfm - $metadataGroup + $generated = @( + 'site', 'nginx.conf' + foreach ($project in $projects.Values) { "restore-$($project.id).log" } + foreach ($entry in $views.Values) { + $entry.directory + "cache-$($entry.tfm)" + "generated-$($entry.tfm)" } ) - $metadataPath = "$stage/framework-metadata.json" - Write-Json $metadataPath @{ metadata = $metadata } - $directories = @($metadata | ForEach-Object { "$stage/$($_.dest)" }) - $cacheFile = if ($MetadataCache) { "$cacheRoot/$tfm.zip" } - $cache = "$work/cache-$tfm" - $cached = $false - if (!$ForceMetadata -and $cacheFile -and (Test-Path -LiteralPath $cacheFile -PathType Leaf)) { - try { - [IO.Compression.ZipFile]::ExtractToDirectory($cacheFile, $cache) - $cachedFingerprint = Get-MetadataFingerprint @($metadata | ForEach-Object { "$cache/$($_.dest)" }) - $cached = $cachedFingerprint -and $cachedFingerprint -ceq (Get-Content -LiteralPath "$cache/fingerprint" -Raw).Trim() - } catch { - Write-Warning "Metadata cache for $view could not be read: $($_.Exception.Message)" - } + Add-Content -LiteralPath "$work/$ownershipFile" -Value $generated + + $sdk = (& dotnet --version).Trim() + if ($LASTEXITCODE -ne 0) { throw 'Could not determine the selected .NET SDK.' } + if ($MetadataCache) { + $cacheVersion = @(Get-FileHash -LiteralPath $PSCommandPath, "$PSScriptRoot/FrameworkViewConventions.ps1", "$PSScriptRoot/DocfxMetadata.ps1", $crossTargetReferences, $resolver, $configPath, $resolvedPath | ForEach-Object Hash) -join ':' + $cacheInputs = "$version/$sdk/$resolverSdk/$cacheVersion/$MetadataCacheKey/$($views.Keys -join ',')" + $cacheId = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($cacheInputs))) + $cacheRoot = "$MetadataCache/$cacheId" + New-Item -ItemType Directory -Path $cacheRoot -Force | Out-Null } - if ($cached) { - foreach ($group in $metadata) { - $destination = "$stage/$($group.dest)" - New-Item -ItemType Directory -Path $destination -Force | Out-Null - Get-ChildItem -LiteralPath "$cache/$($group.dest)" -Force | Copy-Item -Destination $destination -Recurse -Force + $restored = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + foreach ($view in $views.Keys) { + $entry = $views[$view] + $tfm = $entry.tfm + $stage = "$work/$($entry.directory)" + New-Item -ItemType Directory -Path $stage | Out-Null + foreach ($item in Get-ChildItem -LiteralPath $source -Force) { + if ($item.Name -in @('.git', 'bin', 'obj', 'wwwroot', '_site', ($buildDestination -split '/')[0])) { continue } + Copy-Item -LiteralPath $item.FullName -Destination $stage -Recurse -Force } - Write-Host "Reused metadata for $view." - } else { - foreach ($group in $metadata) { - $selected = @($group.src | ForEach-Object { $mapping = $_; $_.files | ForEach-Object { [IO.Path]::GetFullPath((Join-Path $mapping.src $_)) } }) - $versions = foreach ($project in $selected) { - $info = $projects[$project] - if (!$NoRestore -and $restored.Add($project)) { - Invoke-Step "$work/restore-$($info.id).log" dotnet (@('restore', $project) + $info.properties) - } - if (!$mixedTargets) { continue } - $arguments = @('build', $project, '-c', 'Release', '-f', $tfm, '--no-restore') + $info.properties - Invoke-Step "$stage/build-$($info.id).log" dotnet $arguments - $assemblyVersion = & dotnet msbuild $project -nologo -p:Configuration=Release "-p:TargetFramework=$tfm" -t:GetAssemblyVersion -getProperty:AssemblyVersion @($info.properties) - if ($LASTEXITCODE -ne 0 -or $assemblyVersion -notmatch '^\d+(\.\d+){3}$') { throw "Cannot evaluate assembly version for $project." } - $assemblyVersion + $metadata = @( + foreach ($group in $groups) { + $original = $group.config + $destination = "$stage/$($original.dest)" + Clear-StagedMetadata $destination "$source/$($original.dest)/.manifest" + $selected = @($group.projects | Where-Object { $tfm -cin $projects[$_.path].targets }) + if (!$selected.Count) { continue } + $entry.projects += @($selected.relative) + $metadataGroup = ConvertTo-Json $original -Depth 100 | ConvertFrom-Json -AsHashtable + $metadataGroup.src = @($selected | Group-Object root | ForEach-Object { @{ src = $_.Name; files = @($_.Group.relative) } }) + $metadataGroup.properties.TargetFramework = $tfm + $metadataGroup } - if ($versions) { - $distinct = @($versions | Select-Object -Unique) - if ($distinct.Count -ne 1) { throw "The mixed-target workaround requires a common assembly version for '$($group.dest)'." } - $group.properties.AssemblyVersion = $distinct[0] + ) + $metadataPath = "$stage/framework-metadata.json" + Write-Json $metadataPath @{ metadata = $metadata } + $directories = @($metadata | ForEach-Object { "$stage/$($_.dest)" }) + $cacheFile = if ($MetadataCache) { "$cacheRoot/$tfm.zip" } + $cache = "$work/cache-$tfm" + $cached = $false + if (!$ForceMetadata -and $cacheFile -and (Test-Path -LiteralPath $cacheFile -PathType Leaf)) { + try { + [IO.Compression.ZipFile]::ExtractToDirectory($cacheFile, $cache) + $cachedFingerprint = Get-MetadataFingerprint @($metadata | ForEach-Object { "$cache/$($_.dest)" }) + $cached = $cachedFingerprint -and $cachedFingerprint -ceq (Get-Content -LiteralPath "$cache/fingerprint" -Raw).Trim() + } catch { + Write-Warning "Metadata cache for $view could not be read: $($_.Exception.Message)" } } - Write-Json $metadataPath @{ metadata = $metadata } - Invoke-Step "$stage/metadata.log" $docfx @('metadata', $metadataPath, '--noRestore') - $fingerprint = Get-MetadataFingerprint $directories - if (!$fingerprint) { throw "Incomplete metadata for $view." } - if ($cacheFile) { - $temporary = "$work/generated-$tfm" + if ($cached) { foreach ($group in $metadata) { - $destination = "$temporary/$($group.dest)" + $destination = "$stage/$($group.dest)" New-Item -ItemType Directory -Path $destination -Force | Out-Null - Get-ChildItem -LiteralPath "$stage/$($group.dest)" -Recurse -File -Force | Where-Object { $_.Extension -eq '.yml' -or $_.Name -eq '.manifest' } | ForEach-Object { - $output = Join-Path $destination ([IO.Path]::GetRelativePath("$stage/$($group.dest)", $_.FullName)) - New-Item -ItemType Directory -Path (Split-Path -Parent $output) -Force | Out-Null - Copy-Item -LiteralPath $_.FullName -Destination $output - } + Get-ChildItem -LiteralPath "$cache/$($group.dest)" -Force | Copy-Item -Destination $destination -Recurse -Force } - Set-Content -LiteralPath "$temporary/fingerprint" -Value $fingerprint - $archive = "$cacheFile-$([guid]::NewGuid().ToString('N')).tmp" - try { - [IO.Compression.ZipFile]::CreateFromDirectory($temporary, $archive) - [IO.File]::Move($archive, $cacheFile, $true) - } finally { - [IO.File]::Delete($archive) + Write-Host "Reused metadata for $view." + $count = Get-MetadataCount $directories $view + } else { + foreach ($group in $metadata) { + foreach ($project in Get-MappedProjectPaths $group) { + $info = $projects[$project] + if (!$NoRestore -and $restored.Add($project)) { + Invoke-Step "$work/restore-$($info.id).log" dotnet (@('restore', $project) + $info.properties) + } + } } + $count = New-DocfxMetadata $metadata $projects $tfm $view $stage $crossTargetReferences $docfx $cacheFile } - } - $build = ConvertTo-Json $config.build -Depth 100 | ConvertFrom-Json -AsHashtable - if (!$build.globalMetadata) { $build.globalMetadata = @{} } - $build.globalMetadata._frameworkApi = $ApiPath - $build.globalMetadata._frameworkDirectory = $entry.directory - $build.dest = $buildDestination - $build.Remove('output') - $templateFound = $false - $build.template = @($build.template | ForEach-Object { - if ((Split-Path -Leaf $_) -ceq 'ms-style') { $templateFound = $true; 'framework-template/ms-style' } else { $_ } - }) - if (!$templateFound) { throw 'Configure ms-style in the DocFX build template list.' } - New-Item -ItemType Directory -Path "$stage/framework-template" | Out-Null - Copy-Item -LiteralPath "$shared/ms-style" -Destination "$stage/framework-template/ms-style" -Recurse - Write-Json "$stage/framework-build.json" @{ build = $build } - if ($builderImage) { - Invoke-Step "$stage/build.log" docker @('run', '--rm', '--mount', "type=bind,source=$stage,target=/stage", - '-w', '/stage', $BuilderImage, 'docfx', 'build', 'framework-build.json', '--warningsAsErrors') - } else { - Invoke-Step "$stage/build.log" $docfx @('build', "$stage/framework-build.json", '--warningsAsErrors') + $build = ConvertTo-Json $buildSettings -Depth 100 | ConvertFrom-Json -AsHashtable + if (!$build['globalMetadata']) { $build['globalMetadata'] = @{} } + $build.globalMetadata._frameworkApi = $ApiPath + $build.globalMetadata._frameworkDirectory = $entry.directory + $build.dest = $buildDestination + $build.Remove('output') + $build.template = @($build.template | ForEach-Object { + if ($_ -ceq $frameworkTemplate[0]) { 'framework-template/ms-style' } else { $_ } + }) + New-Item -ItemType Directory -Path "$stage/framework-template" | Out-Null + Copy-Item -LiteralPath $templateSource -Destination "$stage/framework-template/ms-style" -Recurse + Write-Json "$stage/framework-build.json" @{ build = $build } + Invoke-Step "$stage/build.log" $docfx @('build', "$stage/framework-build.json") + Write-Host "$view rendered $count metadata UIDs" } - $count = 0 - foreach ($directory in $directories) { $count += (Read-Json "$directory/.manifest").Count } - if (!$count) { throw "Empty DocFX metadata for $view." } - Write-Host "$view rendered $count metadata UIDs" + } finally { + Pop-Location } -} finally { - Pop-Location -} -$defaultView = @($views.Keys.Where({ $views[$_].tfm -ceq $DefaultFramework }))[0] -$site = "$work/site" -Copy-Item -LiteralPath "$work/$($views[$defaultView].directory)/$buildDestination" -Destination $site -Recurse -$routes = foreach ($view in $views.Keys) { - $directory = $views[$view].directory - if ($view -ceq $defaultView) { - ' ~^{0}$ "";' -f [regex]::Escape($view) - continue - } - $native = "$work/$directory/$buildDestination" - $destination = "$site/_frameworks/$directory" - New-Item -ItemType Directory -Path (Split-Path -Parent "$destination/$ApiPath") | Out-Null - Copy-Item -LiteralPath "$native/$ApiPath" -Destination "$destination/$ApiPath" -Recurse - Copy-Item -LiteralPath "$native/xrefmap.yml" -Destination $destination - if (Test-Path -LiteralPath "$native/index.json" -PathType Leaf) { Copy-Item -LiteralPath "$native/index.json" -Destination $destination } - foreach ($asset in Get-ChildItem -LiteralPath $native -Recurse -File) { - $relative = [IO.Path]::GetRelativePath($native, $asset.FullName).Replace('\', '/') - if ($relative.StartsWith("$ApiPath/") -or ($relative -notmatch '^public/' -and $asset.Extension -in '.html', '.json', '.yml', '.xml')) { continue } - if (!(Test-Path -LiteralPath "$site/$relative" -PathType Leaf) -or - (Get-FileHash -LiteralPath "$site/$relative").Hash -cne (Get-FileHash -LiteralPath $asset.FullName).Hash) { - throw "Cannot share $relative with $view." + $defaultView = @($views.Keys)[0] + $site = "$work/site" + Copy-Item -LiteralPath "$work/$($views[$defaultView].directory)/$buildDestination" -Destination $site -Recurse + $routes = foreach ($view in $views.Keys) { + $directory = $views[$view].directory + if ($view -ceq $defaultView) { + ' ~^{0}$ "";' -f [regex]::Escape($view) + continue + } + $native = "$work/$directory/$buildDestination" + $destination = "$site/_frameworks/$directory" + New-Item -ItemType Directory -Path (Split-Path -Parent "$destination/$ApiPath") | Out-Null + Copy-Item -LiteralPath "$native/$ApiPath" -Destination "$destination/$ApiPath" -Recurse + Copy-Item -LiteralPath "$native/xrefmap.yml" -Destination $destination + if (Test-Path -LiteralPath "$native/index.json" -PathType Leaf) { Copy-Item -LiteralPath "$native/index.json" -Destination $destination } + foreach ($asset in Get-ChildItem -LiteralPath $native -Recurse -File) { + $relative = [IO.Path]::GetRelativePath($native, $asset.FullName).Replace('\', '/') + if ($relative.StartsWith("$ApiPath/") -or ($relative -notmatch '^public/' -and $asset.Extension -in '.html', '.json', '.yml', '.xml')) { continue } + if (!(Test-Path -LiteralPath "$site/$relative" -PathType Leaf) -or + (Get-FileHash -LiteralPath "$site/$relative").Hash -cne (Get-FileHash -LiteralPath $asset.FullName).Hash) { + throw "Cannot share $relative with $view." + } } + ' ~^{0}$ /_frameworks/{1};' -f [regex]::Escape($view), $directory } - ' ~^{0}$ /_frameworks/{1};' -f [regex]::Escape($view), $directory -} -$searchRoutes = foreach ($view in $views.Keys) { - $directory = $views[$view].directory - $root = if ($view -ceq $defaultView) { '""' } else { "/_frameworks/$directory" } - ' ~^{0}$ {1};' -f [regex]::Escape($directory), $root + $searchRoutes = foreach ($view in $views.Keys) { + $directory = $views[$view].directory + $root = if ($view -ceq $defaultView) { '""' } else { "/_frameworks/$directory" } + ' ~^{0}$ {1};' -f [regex]::Escape($directory), $root + } + Write-Json "$site/framework-views.json" ([ordered]@{ schemaVersion = 1; apiPath = "/$ApiPath/"; defaultView = $defaultView; viewOrder = @($views.Keys); views = $views }) + (Get-Content -LiteralPath "$PSScriptRoot/framework-views.nginx.conf" -Raw).Replace('__API__', "/$ApiPath/"). + Replace('__VIEWS__', ($routes -join "`n")).Replace('__SEARCH__', ($searchRoutes -join "`n")) | Set-Content -LiteralPath "$work/nginx.conf" + Write-Host "Site: $site" +} finally { + $outputLock.Dispose() } -Write-Json "$site/framework-views.json" ([ordered]@{ schemaVersion = 1; apiPath = "/$ApiPath/"; defaultView = $defaultView; viewOrder = @($views.Keys); views = $views }) -(Get-Content -LiteralPath "$PSScriptRoot/framework-views.nginx.conf" -Raw).Replace('__API__', "/$ApiPath/"). - Replace('__VIEWS__', ($routes -join "`n")).Replace('__SEARCH__', ($searchRoutes -join "`n")) | Set-Content -LiteralPath "$work/nginx.conf" -Write-Host "Site: $site" diff --git a/framework-views/DocfxMetadata.ps1 b/framework-views/DocfxMetadata.ps1 new file mode 100644 index 0000000..e2e0e58 --- /dev/null +++ b/framework-views/DocfxMetadata.ps1 @@ -0,0 +1,160 @@ +function Write-Json([string] $Path, $Value) { + ConvertTo-Json -InputObject $Value -Depth 100 | Set-Content -LiteralPath $Path +} + +function Read-Json([string] $Path) { + Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json -AsHashtable -NoEnumerate +} + +function Read-MSBuildJson([string[]] $Output, [string] $Project) { + # SDK first-run messages and project warnings can precede the property JSON. + $outputText = $Output -join "`n" + $json = [regex]::Match($outputText, '(?ms)^\{\n.*?^\}$') + if (!$json.Success) { throw "MSBuild did not return evaluation JSON for ${Project}: $outputText" } + $json.Value | ConvertFrom-Json +} + +function Get-MappedProjectPaths($Group) { + foreach ($mapping in $Group.src) { + foreach ($file in $mapping.files) { [IO.Path]::GetFullPath((Join-Path $mapping.src $file)) } + } +} + +function Clear-StagedMetadata([string] $Destination, [string] $Manifest) { + Assert-SafeOutputPath $Destination + if (!(Test-Path -LiteralPath $Destination -PathType Container)) { return } + $generatedToc = if (Test-Path -LiteralPath $Manifest -PathType Leaf) { Join-Path $Destination 'toc.yml' } + Get-ChildItem -LiteralPath $Destination -Recurse -File -Force | Where-Object { + $_.FullName -ceq $generatedToc -or $_.Name -eq '.manifest' -or + ($_.Extension -eq '.yml' -and (Get-Content -LiteralPath $_.FullName -TotalCount 1) -match '^### YamlMime:(ManagedReference|ApiPage|TableOfContent)\s*$') + } | Remove-Item -Force +} + +function Repair-DocfxProjectReferences($Metadata, $Projects, [string] $Tfm, [string] $Stage, [string] $TargetsFile, + [string[]] $MissingProjects) { + $retry = $false + foreach ($group in $Metadata) { + $availableHooks = [Collections.Generic.List[string]]::new() + foreach ($hook in 'CustomAfterMicrosoftCommonTargets', 'CustomBeforeMicrosoftCommonTargets') { + if ($hook -notin $group.properties.Keys) { $availableHooks.Add($hook) } + } + $enableReferenceAssemblies = $false + $affected = @( + foreach ($project in Get-MappedProjectPaths $group) { + $info = $Projects[$project] + $log = "$Stage/references-$($info.id).log" + Invoke-Step $log dotnet (@('msbuild', $project, '-nologo', "-p:TargetFramework=$Tfm", + '-p:DesignTimeBuild=true', '-p:BuildProjectReferences=false', '-t:PrepareProjectReferences', + '-getItem:_MSBuildProjectReferenceExistent', '-getProperty:CustomAfterMicrosoftCommonTargets,CustomBeforeMicrosoftCommonTargets,ProduceReferenceAssembly') + $info.properties) + $evaluation = Read-MSBuildJson (Get-Content -LiteralPath $log) $project + $references = @($evaluation.Items._MSBuildProjectReferenceExistent | Where-Object { + $_.ReferenceOutputAssembly -eq 'true' -and $_.NearestTargetFramework + }) + if ($references | Where-Object NearestTargetFramework -CNE $Tfm | Select-Object -First 1) { $project } + if ($MissingProjects.Count -and 'ProduceReferenceAssembly' -notin $group.properties.Keys -and + $evaluation.Properties.ProduceReferenceAssembly -eq 'false') { + # With reference assemblies disabled, Roslyn can lose same-target edges even after a build. + if ($references | Where-Object { + $_.NearestTargetFramework -ceq $Tfm -and + ($_.FullPath -cin $MissingProjects -or ($IsWindows -and $_.FullPath -in $MissingProjects)) + } | Select-Object -First 1) { $enableReferenceAssemblies = $true } + } + foreach ($hook in $availableHooks.ToArray()) { + $path = $evaluation.Properties.$hook + if ($path -and (Test-Path -LiteralPath ([IO.Path]::GetFullPath($path, (Split-Path -Parent $project))) -PathType Leaf)) { + [void]$availableHooks.Remove($hook) + } + } + } + ) + if ($affected.Count) { + if (!$availableHooks.Count) { + throw "Cross-target DocFX recovery needs an unused CustomAfterMicrosoftCommonTargets or CustomBeforeMicrosoftCommonTargets hook. See '$Stage/metadata.log'." + } + foreach ($project in $affected) { + $info = $Projects[$project] + $arguments = @('build', $project, '-f', $Tfm, '--no-restore') + $info.properties + if ($enableReferenceAssemblies) { $arguments += '-p:ProduceReferenceAssembly=true' } + Invoke-Step "$Stage/build-$($info.id).log" dotnet $arguments + } + $group.properties[$availableHooks[0]] = $TargetsFile + } + if ($enableReferenceAssemblies) { $group.properties.ProduceReferenceAssembly = 'true' } + if ($affected.Count -or $enableReferenceAssemblies) { $retry = $true } + } + $retry +} + +function Get-MetadataFingerprint([string[]] $Directories) { + $entries = foreach ($directory in $Directories) { + if (!(Test-Path -LiteralPath "$directory/.manifest" -PathType Leaf)) { return } + foreach ($file in Get-ChildItem -LiteralPath $directory -Recurse -File -Force | Where-Object { $_.Extension -eq '.yml' -or $_.Name -eq '.manifest' } | Sort-Object FullName -CaseSensitive) { + "$([IO.Path]::GetRelativePath($directory, $file.FullName).Replace('\', '/'))=$((Get-FileHash -LiteralPath $file.FullName).Hash)" + } + } + [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes(($entries -join "`n")))) +} + +function Get-MetadataCount([string[]] $Directories, [string] $View) { + $count = 0 + foreach ($directory in $Directories) { $count += (Read-Json "$directory/.manifest").Count } + if (!$count) { throw "Empty DocFX metadata for $View." } + $count +} + +function New-DocfxMetadata($Metadata, $Projects, [string] $Tfm, [string] $View, [string] $Stage, + [string] $TargetsFile, [string] $Docfx, [string] $CacheFile) { + $metadataPath = "$Stage/framework-metadata.json" + $metadataLog = "$Stage/metadata.log" + $metadataArguments = @('metadata', $metadataPath, '--noRestore') + $directories = @($Metadata | ForEach-Object { "$Stage/$($_.dest)" }) + $missingReference = 'Found project reference without a matching metadata reference' + $ansiColor = '\x1b\[[0-9;:]*m' + + $exitCode = Invoke-Step $metadataLog $Docfx $metadataArguments -ReturnExitCode + # DocFX colorizes CI output. Keep the original log but parse undecorated diagnostics. + $metadataOutput = (Get-Content -LiteralPath $metadataLog) -replace $ansiColor + # DocFX may succeed with incomplete output or fail with duplicate assembly identities. + $referenceWarnings = @($metadataOutput | Select-String -Pattern "$missingReference(?::\s*(.+))?") + if ($referenceWarnings.Count) { + $missingProjects = @($referenceWarnings | ForEach-Object { $_.Matches[0].Groups[1].Value.Trim() }) + if (!(Repair-DocfxProjectReferences $Metadata $Projects $Tfm $Stage $TargetsFile $missingProjects)) { + throw "DocFX metadata for $View has unresolved project references and recovery was unavailable. Check the project references and target frameworks in '$metadataLog'." + } + Move-Item -LiteralPath $metadataLog -Destination "$Stage/metadata-before-recovery.log" + foreach ($directory in $directories) { Clear-StagedMetadata $directory "$directory/.manifest" } + Write-Json $metadataPath @{ metadata = $Metadata } + $exitCode = Invoke-Step $metadataLog $Docfx $metadataArguments -ReturnExitCode + $metadataOutput = (Get-Content -LiteralPath $metadataLog) -replace $ansiColor + if ($metadataOutput | Select-String -SimpleMatch $missingReference -Quiet) { + throw "DocFX metadata for $View still has unresolved project references after recovery. Check '$metadataLog' and '$Stage/metadata-before-recovery.log'." + } + } + if ($exitCode -ne 0 -or ($metadataOutput -match '^error:')) { + throw "DocFX metadata failed for $View. See $metadataLog." + } + $fingerprint = Get-MetadataFingerprint $directories + if (!$fingerprint) { throw "Incomplete metadata for $View. See $metadataLog." } + $count = Get-MetadataCount $directories $View + if (!$CacheFile) { return $count } + + $temporary = Join-Path (Split-Path -Parent $Stage) "generated-$Tfm" + foreach ($group in $Metadata) { + $destination = "$temporary/$($group.dest)" + New-Item -ItemType Directory -Path $destination -Force | Out-Null + Get-ChildItem -LiteralPath "$Stage/$($group.dest)" -Recurse -File -Force | Where-Object { $_.Extension -eq '.yml' -or $_.Name -eq '.manifest' } | ForEach-Object { + $output = Join-Path $destination ([IO.Path]::GetRelativePath("$Stage/$($group.dest)", $_.FullName)) + New-Item -ItemType Directory -Path (Split-Path -Parent $output) -Force | Out-Null + Copy-Item -LiteralPath $_.FullName -Destination $output + } + } + Set-Content -LiteralPath "$temporary/fingerprint" -Value $fingerprint + $archive = "$CacheFile-$([guid]::NewGuid().ToString('N')).tmp" + try { + [IO.Compression.ZipFile]::CreateFromDirectory($temporary, $archive) + [IO.File]::Move($archive, $CacheFile, $true) + } finally { + [IO.File]::Delete($archive) + } + $count +} diff --git a/framework-views/FrameworkViewConventions.ps1 b/framework-views/FrameworkViewConventions.ps1 new file mode 100644 index 0000000..0737c11 --- /dev/null +++ b/framework-views/FrameworkViewConventions.ps1 @@ -0,0 +1,85 @@ +function Get-ApiPath($Metadata) { + if (!$Metadata) { throw 'Configure at least one project metadata group in docfx.json.' } + $common = $null + foreach ($group in $Metadata) { + $destination = $group['dest'] + if ($destination -isnot [string] -or $destination -cnotmatch '^[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*\z') { + throw "Invalid metadata.dest '$destination'. Use a relative API directory with forward slashes and URL-safe directory names." + } + $segments = $destination.Split('/') + if ($null -eq $common) { + $common = $segments + continue + } + $length = 0 + while ($length -lt [Math]::Min($common.Count, $segments.Count) -and $common[$length] -ceq $segments[$length]) { + $length++ + } + if (!$length) { throw 'Metadata destinations have no common API directory. Put all metadata.dest paths under one directory in docfx.json.' } + $common = $common[0..($length - 1)] + } + if ($common[0] -in 'public', '_frameworks', '_framework-search') { + throw "Metadata destinations use the reserved directory '$($common[0])'. Choose a different API directory in docfx.json." + } + $common -join '/' +} + +function Get-FrameworkView([string] $Tfm, [string] $Project) { + if ($Tfm -cmatch '^(net)([1-4])([0-9])([0-9]?)$') { + $patch = if ($Matches[4]) { $Matches[4] } else { '0' } + return @{ tfm = $Tfm; family = 3; version = [version]("$($Matches[2]).$($Matches[3]).$patch"); view = $Tfm; directory = $Tfm } + } + if ($Tfm -cmatch '^(net|netcoreapp|netstandard)(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$') { + $name = $Matches[1] + $major = $Matches[2] + $minor = $Matches[3] + $version = $null + if ([version]::TryParse("$major.$minor", [ref] $version) -and $version.Major -ge 1) { + $family = @('net', 'netcoreapp', 'netstandard').IndexOf($name) + if ($family -eq 0 -and $version.Major -lt 5) { + $family = 3 + $version = [version]("$major.$minor.0") + } + $directory = if ($family -eq 0 -and $version.Minor -eq 0) { "net$major" } else { $Tfm } + return @{ tfm = $Tfm; family = $family; version = $version; view = "$name-$major.$minor"; directory = $directory } + } + } + throw "Unsupported target framework '$Tfm' in '$Project'. Framework views require unqualified .NET, .NET Core, .NET Standard or .NET Framework TFMs. Check the evaluated project targets and metadata.src mappings in docfx.json." +} + +function Get-OrderedFrameworkViews($Frameworks) { + $Frameworks | Sort-Object { $_.family }, @{ Expression = { $_.version }; Descending = $true }, { $_.tfm } -Unique +} + +function Test-PathWithin([string] $Directory, [string] $Path) { + $relative = [IO.Path]::GetRelativePath($Directory, $Path) + $relative -ne '..' -and !$relative.StartsWith("..$([IO.Path]::DirectorySeparatorChar)") -and ![IO.Path]::IsPathRooted($relative) +} + +function Assert-SafeOutputPath([string] $Path) { + for ($ancestor = $Path; $ancestor; $ancestor = [IO.Path]::GetDirectoryName($ancestor)) { + $item = Get-Item -LiteralPath $ancestor -Force -ErrorAction SilentlyContinue + if ($item -and (!$item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint))) { + throw "Framework output requires real directories. '$ancestor' is a file or link." + } + } +} + +function Get-FrameworkOutputEntries([string] $Path, [string] $OwnershipFile, [string] $LockFile) { + $entries = @(Get-ChildItem -LiteralPath $Path -Force | Where-Object Name -CNE $LockFile) + if (!$entries.Count) { return } + $marker = $entries | Where-Object Name -CEQ $OwnershipFile + if (!$marker -or $marker.PSIsContainer -or ($marker.Attributes -band [IO.FileAttributes]::ReparsePoint) -or + (Get-Content -LiteralPath $marker.FullName -TotalCount 1) -cne 'docfx-framework-views-v1') { + throw "Framework output directory must be empty or owned by the generator. Choose a dedicated directory: $Path" + } + $owned = @(Get-Content -LiteralPath $marker.FullName | Select-Object -Skip 1) + foreach ($entry in $entries | Where-Object Name -CNE $OwnershipFile) { + if ($entry.Name -cnotin $owned) { + throw "Unexpected item in the framework output directory. Move '$($entry.FullName)' before rebuilding." + } + $entry + } + $links = Get-ChildItem -LiteralPath $Path -Force -Recurse -Attributes ReparsePoint | Select-Object -First 1 + if ($links) { throw "Framework output contains a link. Move '$($links.FullName)' before rebuilding." } +} diff --git a/framework-views/KeepCrossTargetReferences.targets b/framework-views/KeepCrossTargetReferences.targets new file mode 100644 index 0000000..206fae4 --- /dev/null +++ b/framework-views/KeepCrossTargetReferences.targets @@ -0,0 +1,13 @@ + + + + + <_DocfxCrossTargetReference Include="@(ReferencePath)" + Condition="'%(ReferencePath.NearestTargetFramework)' != '' and + '%(ReferencePath.NearestTargetFramework)' != '$(TargetFramework)' and + '%(ReferencePath.OriginalProjectReferenceItemSpec)' != ''" /> + + + + diff --git a/framework-views/README.md b/framework-views/README.md index 743d7fa..5ce3330 100644 --- a/framework-views/README.md +++ b/framework-views/README.md @@ -6,64 +6,63 @@ Use PowerShell 7, Git, DocFX CLI **2.81.0** installed as a .NET tool, and the SDK selected by the consumer's `global.json` or required by its projects. Install .NET 10 or later alongside an older project SDK for the file-based discovery tool. A .NET 11 consumer needs a .NET 11 SDK. The DocFX CLI also needs its .NET 10 runtime. Install it with `dotnet tool install --tool-path docfx --version 2.81.0` and put that directory on `PATH`, or install it as a global tool. The generator reads the CLI's file-mapping libraries from its tool store. -From the consumer root, download the approved source archive by full commit SHA and run the generator. Keep the archive layout so the generator can find `templates/ms-style/`. For local development, set `$distribution` to a DocFX checkout. Use an empty output directory outside the directory containing `docfx.json`. +Run the generator from the consumer repository root. Use the script's installed path if it lives outside the checkout. Keep the distribution layout so the generator can find the bundled template. ```powershell -$commit = '' -$releaseRoot = Join-Path ([IO.Path]::GetTempPath()) "docfx-source-$([guid]::NewGuid())" -New-Item -ItemType Directory -Path $releaseRoot | Out-Null -$archive = Join-Path $releaseRoot 'docfx.zip' -Invoke-WebRequest "https://codeload.github.com/codebeltnet/docfx/zip/$commit" -OutFile $archive -Expand-Archive -LiteralPath $archive -DestinationPath $releaseRoot -$distribution = Join-Path $releaseRoot "docfx-$commit" - -pwsh -NoProfile -File "$distribution/framework-views/Build-DocfxFrameworkViews.ps1" ` - -DocfxConfig .docfx/docfx.json -SettingsPath .docfx/framework-views.json ` - -OutputRoot .artifacts/framework-views +pwsh -File Build-DocfxFrameworkViews.ps1 ``` -### Settings +This reads `.docfx/docfx.json` and writes to `.bot/docfx`, relative to the working directory. Keep `.bot/` covered by the repository's existing ignore convention. CI and isolated builds can specify both paths. -```json -{ - "apiPath": "api", - "defaultFramework": "net11.0", - "frameworks": ["net11.0", "net10.0", "netstandard2.1", "netstandard2.0"], - "alignAssemblyVersion": false -} +```powershell +pwsh -File Build-DocfxFrameworkViews.ps1 ` + -DocfxConfig .docfx/docfx.json ` + -OutputRoot .bot/docfx ``` -| Field | Contract | -| --- | --- | -| `apiPath` | Required public API root, without leading or trailing slashes. Every `metadata.dest` must be at or below it, for example `api/dotnet` or `api/extensions/dotnet`. | -| `defaultFramework` | Required declared TFM used for requests without a view. | -| `frameworks` | Optional ordered list of declared TFMs. Include the default. With the field omitted, the default appears first and discovery supplies the rest. View IDs support unqualified `net`, `netstandard`, `netcoreapp`, and compact .NET Framework TFMs. Supply an explicit list of supported TFMs when discovery includes platform-qualified targets. | -| `alignAssemblyVersion` | Optional opt-in for mixed-target project graphs with a common assembly version. For mixed views, a Release build supplies the assembly version to the corresponding metadata group. | -| `templatePath` | Optional path to a compatible `ms-style` override, relative to the settings file or absolute. Use it to test local template changes. | -| `builderImage` | Optional version-and-digest-pinned builder for rendering HTML. Discovery, restore and metadata still run in the calling environment. The image supplies its `ms-style` when `templatePath` is omitted. Its DocFX CLI must report 2.81.0. | +An output directory must be dedicated to the generator and start empty. Subsequent invocations reuse the directory, including after a failed build. The generator records the artifacts it owns and refuses to clean a directory with unexpected entries or links. Use a separate directory for persistent metadata caches. + +## DocFX configuration and framework precedence + +The generator uses the deepest common directory of the `metadata.dest` paths as the public API root. For example, `api/dotnet/runtime` and `api/dotnet/utilities` give `/api/dotnet/`. Use relative, URL-safe destinations under one common API directory. A single metadata group uses its own destination as the API root. + +DocFX owns project mappings, filters, exclusions, overwrites and other metadata options. MSBuild supplies each mapped project's evaluated target frameworks, including inherited values. Remove any `TargetFramework` metadata property so the generator can choose the target per view. A project contributes documentation only to its evaluated targets. Unsupported TFMs, including platform-qualified TFMs, fail with the project path and the target in the diagnostic. + +The default view is the first discovered target in this order. The same order determines fallback precedence. + +1. Modern .NET, by descending numeric version +2. .NET Core, by descending numeric version +3. .NET Standard, by descending numeric version +4. .NET Framework, by descending numeric version + +For example, the order is `net11.0`, `net10.0`, `net9.0`, `netcoreapp3.1`, `netstandard2.1`, `netstandard2.0`, `net481`, `net48`, `net462`. New unqualified versions follow the same rules when the installed SDK and DocFX support them. -`docfx.json` owns metadata group mappings, exclusions, filters, properties, and destinations. Include `ms-style` in `build.template` and omit the global `TargetFramework` from metadata groups. Keep build content, resources, and consumer template overlays under the configuration directory. Project sources can sit outside it. Omit a site-local entry from `build.xref` if it can resolve UIDs from another view. A project contributes metadata only to its declared targets. Duplicate UIDs within a view have the same constraints as a standard DocFX build. +Keep build content, resources, and consumer template overlays under the configuration directory. Project sources can sit outside it. Omit a site-local entry from `build.xref` if it can resolve UIDs from another view. Duplicate UIDs within a view have the same constraints as a standard DocFX build. -The generator restores selected projects by default. Use `-NoRestore` when their restore assets already match the build inputs. To reuse metadata, pass `-MetadataCache ` and `-MetadataCacheKey `. Keep the cache outside the DocFX input directory. The caller's fingerprint must cover the source tree and revision, imported build files, SDK pins and restore inputs, and metadata filters. The generator also hashes its metadata implementation, DocFX config and resolved mappings, selected SDKs, CLI version, and relevant framework settings. Cached metadata is verified for each view. A damaged entry is regenerated independently. `-ForceMetadata` regenerates and refreshes entries. HTML is rendered each time. Use a fresh output directory when retrying a partial build. +### Metadata generation and caching + +The generator restores selected projects by default. Use `-NoRestore` when their restore assets already match the build inputs. If DocFX reports an unresolved project reference and MSBuild confirms a cross-target reference, the generator builds the affected project and retries with MSBuild's selected dependency DLL. This avoids duplicate assembly identities from Roslyn's design-time builds while retaining each assembly's own version. The retry requires an unused `CustomAfterMicrosoftCommonTargets` or `CustomBeforeMicrosoftCommonTargets` MSBuild extension point for the affected metadata group. For a diagnosed same-target reference with SDK reference assemblies disabled, DocFX can retry in reference-assembly mode without a recovery build. + +An unresolved project reference fails generation when recovery is unavailable or when the retry still reports the warning. The error points to the metadata logs. A view's metadata enters the cache only after validation succeeds. Other DocFX warnings remain non-fatal. + +To reuse metadata, pass `-MetadataCache ` and `-MetadataCacheKey `. The caller's fingerprint must cover source files and revision, imported build files, SDK pins, restore inputs and metadata filters. The generator also hashes its metadata implementation, DocFX config, resolved mappings, SDK versions and discovered framework order. It validates each cached view and regenerates a damaged entry independently. Use `-ForceMetadata` to refresh entries. HTML is rendered on every invocation. ### Template compatibility -The generator checks DocFX 2.81.0 and the template root's [`framework-views.compat`](../templates/ms-style/framework-views.compat) marker before discovery. The current marker is `framework-views-v1/docfx-2.81.0`. Pin a full source commit or builder image digest for releases. To test unreleased template changes, set `templatePath` to a working copy that implements the same contract and carries the marker. This check also applies to templates supplied by a rendering image. CLI upgrades require verifying the generator's project mapping APIs and the template's search integration before updating the contract. +Include `templates/ms-style` in the DocFX `build.template` list. The generator uses an existing compatible `ms-style` directory at the configured path, or the bundled template when the conventional entry is absent from the checkout. Other template entries stay in the authored order. DocFX must report 2.81.0, and the template's [`framework-views.compat`](../templates/ms-style/framework-views.compat) marker must read `framework-views-v1/docfx-2.81.0`. CLI upgrades require checking the project mapping APIs and the template's search integration. ## Run in the builder image The shared builder image distributes the same script and packaging assets at `/opt/docfx/framework-views/` and matching templates at `/opt/docfx/templates/`. It includes PowerShell 7, the .NET 10 and .NET 11 SDKs, and DocFX 2.81.0. The consumer's `global.json` can select an installed project SDK independently of the resolver. For other SDK pins, run from the source distribution with the required SDKs on the host or supply them in a derived builder. -Use the approved image index digest from [Publish and verify the builder image](../README.md#publish-and-verify-the-builder-image). For branch testing, [build the image locally](../README.md#build-the-builder-image-locally) and substitute `docfx-local:2.81.0` below. +Use the approved image index digest from the [CI/CD release and deployment lifecycle](../README.md#cicd-release-and-deployment-lifecycle). See [Docker image versioning](../README.md#docker-image-versioning) for the trade-offs between convenience tags (`codebeltnet/docfx:2`, `:2.81`, `:2.81.0`, `:latest`), engine-qualified tags (`:2-v1.1.0`, `:2.81-v1.1.0`, `:2.81.0-v1.1.0`), and digest-pinned references; existing convenience-tag references remain supported and migration is optional. The `1.1.0` example below illustrates the naming contract and is not publicly available until release publication occurs. For branch testing, [build the image locally](../README.md#build-the-builder-image-locally) with `-Tag docfx-local -EngineVersion 1.1.0` and substitute `docfx-local:2.81.0-v1.1.0` (or `docfx-local:2.81.0`) below. -From the consumer root, omit `builderImage` from the settings to run discovery, restore, metadata generation, rendering, and site packaging inside one container. Mount the checkout writable for restore and build outputs. +Run the entire generator in the selected image. Mount the consumer checkout writable for restore and build outputs. ```powershell -$builder = 'codebeltnet/docfx:2.81.0@sha256:' +$builder = 'codebeltnet/docfx:2.81.0-v1.1.0@sha256:' docker run --rm --mount "type=bind,source=$($PWD.Path),target=/workspace" -w /workspace $builder ` - pwsh -NoProfile -File /opt/docfx/framework-views/Build-DocfxFrameworkViews.ps1 ` - -DocfxConfig .docfx/docfx.json -SettingsPath .docfx/framework-views.json ` - -OutputRoot .artifacts/framework-views + pwsh -NoProfile -File /opt/docfx/framework-views/Build-DocfxFrameworkViews.ps1 ``` ## Outputs and hosting @@ -76,14 +75,27 @@ docker run --rm --mount "type=bind,source=$($PWD.Path),target=/workspace" -w /wo Use [framework-views.Dockerfile](framework-views.Dockerfile) with a context containing `site/` and `nginx.conf`. It uses a pinned NGINX base by default, accepts `NGINX_IMAGE` as an explicit build argument, checks for the manifest and runs `nginx -t`. A consumer can provide its own Dockerfile or server configuration and preserve the public path, routing, search worker and cache contract. ```powershell -docker build -f /path/to/docfx/framework-views/framework-views.Dockerfile -t my-docs:local .artifacts/framework-views +docker build -f /path/to/docfx/framework-views/framework-views.Dockerfile -t my-docs:local .bot/docfx docker run --rm -p 127.0.0.1:8080:8080 my-docs:local ``` ## OCI action integration -To adopt this distribution for multi-framework builds in the [`docfx-oci-build` action](https://github.com/codebeltnet/docfx-oci-build), pin it by full commit SHA. The action integration resolves the consumer config and settings against its workspace, invokes the generator above with absolute paths and an empty output directory, and propagates its exit status. Optional cache inputs use the same generator switches. Runner prerequisites and optional digest-pinned rendering match the source invocation. +Use an updated action and compatible builder image. Pin the action by full release commit SHA. Add these inputs alongside the existing version, revision and output inputs. [DocFX OCI build action](https://github.com/codebeltnet/docfx-oci-build) + +```yaml +with: + docfx-config: .docfx/docfx.json + framework-views: true +``` + +The action runs the bundled generator inside the builder image and stages the generated `site/` and `nginx.conf` as the OCI build context. It selects the bundled `framework-views.Dockerfile` by default. An explicit workspace-relative `dockerfile` overrides packaging and can use the named `docfx-source` build context for authored DocFX files. The action owns revision checks, Buildx orchestration, OCI annotations, archive output, checksums, and artifact verification. Omitting the opt-in or setting it to `false` uses ordinary DocFX. + +## Migrate existing framework views -The action stages `site/` and `nginx.conf` as the primary OCI build context. Its `bundled-framework-views` option resolves to `framework-views/framework-views.Dockerfile` from the same pinned source. A custom Dockerfile can use the `docfx-source` named context for the directory containing the consumer's DocFX configuration. The action owns release revision checks, Buildx orchestration, OCI annotations, archive output, checksums, and artifact verification. +1. Remove the authored framework settings file and its command-line argument. Keep the generated runtime manifest in the packaged site. +2. Use the existing DocFX destinations to establish a common API directory. Review the default view and fallback order if they were previously set by hand. +3. Run locally with the defaults or pass explicit configuration and output paths in CI. Point packaging at the new output directory. +4. In the OCI action, change the settings-file input to `framework-views: true`. Omit the Dockerfile input for bundled packaging, or retain the path to a custom Dockerfile. Update the action and its builder image together. -The [regression guide](../tests/framework-view/README.md) covers synthetic projects, SDK pins, the isolated Cuemon fixture, and browser behavior. +The [regression guide](../tests/framework-view/README.md) covers the synthetic projects, SDK pins, Cuemon fixture, and browser behavior. diff --git a/templates/ms-style/README.md b/templates/ms-style/README.md index 61d94ab..f53411e 100644 --- a/templates/ms-style/README.md +++ b/templates/ms-style/README.md @@ -53,7 +53,7 @@ This is the only content-model migration required. Existing DocFX YAML, Markdown ## Framework views -The opt-in [DocFX framework views generator](../../framework-views/README.md) supplies `_frameworkApi`, `_frameworkDirectory`, and `/framework-views.json`. On API pages, the template puts the framework selector above the TOC and uses the native xref map for each view to find the current API. The selector follows the configured newest-to-oldest order, keeps the reader in the current view when that is the best available choice, and reports which view it displays. Availability refers to published documentation. +The opt-in [DocFX framework views generator](../../framework-views/README.md) supplies `_frameworkApi`, `_frameworkDirectory`, and `/framework-views.json`. On API pages, the template puts the framework selector above the TOC and uses the native xref map for each view to find the current API. The selector follows the discovered framework precedence, keeps the reader in the current view when that is the best available choice, and reports which view it displays. Availability refers to published documentation. Each view keeps the public API pathname and uses `?view=` for explicit selection. The query-aware NGINX configuration also exposes the native search index for the selected framework. The template applies public URLs to search destinations and their secondary labels. Without framework build metadata, the template uses the standard DocFX navigation and search. diff --git a/tests/BuildAndPushDocfxImage.Tests.ps1 b/tests/BuildAndPushDocfxImage.Tests.ps1 new file mode 100644 index 0000000..ad7a782 --- /dev/null +++ b/tests/BuildAndPushDocfxImage.Tests.ps1 @@ -0,0 +1,512 @@ +BeforeAll { + $repoRoot = (Resolve-Path -LiteralPath "$PSScriptRoot/..").Path + $buildScript = (Resolve-Path -LiteralPath "$PSScriptRoot/../BuildAndPushDocfxImage.ps1").Path + $modulePath = (Resolve-Path -LiteralPath "$PSScriptRoot/../tools/DocfxImage.psm1").Path + Import-Module $modulePath -Force + + $validRevision = 'a' * 40 + $validIndexDigest = 'sha256:' + ('1' * 64) + $arm64Digest = 'sha256:' + ('2' * 64) + $amd64Digest = 'sha256:' + ('3' * 64) + $attestationDigest = 'sha256:' + ('4' * 64) + + function Get-ArgumentValues([string[]] $Arguments, [string] $Flag) { + $values = [System.Collections.Generic.List[string]]::new() + for ($i = 0; $i -lt $Arguments.Count - 1; $i++) { + if ($Arguments[$i] -ceq $Flag) { + $values.Add($Arguments[$i + 1]) + } + } + ,$values.ToArray() + } +} + +Describe 'BuildAndPushDocfxImage versioning, OCI build-only, and safeguards' { + BeforeEach { + $global:DocfxBuildTestState = @{ + DockerCalls = [System.Collections.Generic.List[object]]::new() + SkopeoCalls = [System.Collections.Generic.List[object]]::new() + OciCalls = [System.Collections.Generic.List[object]]::new() + GitState = @{ + ExitCode = 0 + Output = $validRevision + } + DockerState = @{ + HasPushed = $false + BuildExitCode = 0 + BuildDigest = $validIndexDigest + IndexDigest = $validIndexDigest + IndexMediaType = 'application/vnd.oci.image.index.v1+json' + PreflightResponses = @{} + ManifestResponses = @{} + ImageResponses = @{} + Manifests = @( + @{ + mediaType = 'application/vnd.oci.image.manifest.v1+json' + digest = $arm64Digest + platform = @{ os = 'linux'; architecture = 'arm64' } + } + @{ + mediaType = 'application/vnd.oci.image.manifest.v1+json' + digest = $amd64Digest + platform = @{ os = 'linux'; architecture = 'amd64' } + } + @{ + mediaType = 'application/vnd.oci.image.manifest.v1+json' + digest = $attestationDigest + annotations = @{ 'vnd.docker.reference.type' = 'attestation-manifest' } + platform = @{ os = 'unknown'; architecture = 'unknown' } + } + ) + ImageLabels = @{ + 'org.opencontainers.image.version' = '1.1.0' + 'net.codebelt.docfx.engine.version' = '1.1.0' + 'net.codebelt.docfx.cli.version' = '2.81.0' + 'org.opencontainers.image.revision' = $validRevision + } + } + } + + Mock -ModuleName DocfxImage git { + $global:LASTEXITCODE = $global:DocfxBuildTestState.GitState.ExitCode + return $global:DocfxBuildTestState.GitState.Output + } + + Mock -ModuleName DocfxImage docker { + $state = $global:DocfxBuildTestState + $ds = $state.DockerState + $callArgs = @($args) + $state.DockerCalls.Add($callArgs) + $global:LASTEXITCODE = 0 + + if ($callArgs.Count -ge 1 -and $callArgs[0] -ceq 'info') { + return 'linux/x86_64' + } + if ($callArgs.Count -ge 2 -and $callArgs[0] -ceq 'image' -and $callArgs[1] -ceq 'inspect') { + return (@(@{ Id = 'sha256:' + ('7' * 64); Size = 123456 }) | ConvertTo-Json -Depth 4) + } + if ($callArgs.Count -ge 1 -and ($callArgs[0] -ceq 'load' -or $callArgs[0] -ceq 'tag')) { + return + } + if ($callArgs.Count -ge 2 -and $callArgs[0] -ceq 'buildx' -and $callArgs[1] -ceq 'build') { + if ($ds.BuildExitCode -ne 0) { + $global:LASTEXITCODE = $ds.BuildExitCode + return + } + if ($callArgs -contains '--push') { + $ds.HasPushed = $true + } + $outIndex = [Array]::IndexOf($callArgs, '--output') + if ($outIndex -ge 0 -and $callArgs[$outIndex + 1] -match 'dest=(.+)$') { + $destPath = $Matches[1] + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $destPath) | Out-Null + Set-Content -LiteralPath $destPath -Value 'synthetic-oci-tar' + } + $metadataIndex = [Array]::IndexOf($callArgs, '--metadata-file') + if ($metadataIndex -ge 0) { + $metadataPath = $callArgs[$metadataIndex + 1] + @{ 'containerimage.digest' = $ds.BuildDigest } | + ConvertTo-Json | + Set-Content -LiteralPath $metadataPath + } + return + } + if ($callArgs.Count -ge 3 -and $callArgs[0] -ceq 'buildx' -and $callArgs[1] -ceq 'imagetools' -and $callArgs[2] -ceq 'inspect') { + $formatIndex = [Array]::IndexOf($callArgs, '--format') + $format = $callArgs[$formatIndex + 1] + $reference = $callArgs[-1] + + if ($format -ceq '{{json .Manifest}}') { + if (-not $ds.HasPushed) { + if ($ds.PreflightResponses.ContainsKey($reference)) { + $response = $ds.PreflightResponses[$reference] + $global:LASTEXITCODE = $response.ExitCode + return $response.Output + } + $global:LASTEXITCODE = 1 + return "ERROR: docker.io/${reference}: not found" + } + if ($ds.ManifestResponses.ContainsKey($reference)) { + $response = $ds.ManifestResponses[$reference] + $global:LASTEXITCODE = $response.ExitCode + return $response.Output + } + return (@{ + schemaVersion = 2 + mediaType = $ds.IndexMediaType + digest = $ds.IndexDigest + manifests = $ds.Manifests + } | ConvertTo-Json -Depth 6) + } + + if ($format -ceq '{{json .Image}}') { + if ($ds.ImageResponses.ContainsKey($reference)) { + $response = $ds.ImageResponses[$reference] + $global:LASTEXITCODE = $response.ExitCode + return $response.Output + } + $arch = if ($reference.EndsWith("@$arm64Digest")) { 'arm64' } else { 'amd64' } + return (@{ + os = 'linux' + architecture = $arch + config = @{ Labels = $ds.ImageLabels } + } | ConvertTo-Json -Depth 6) + } + } + } + } + + AfterEach { + Remove-Variable DocfxBuildTestState -Scope Global -ErrorAction SilentlyContinue + } + + Context 'Local builds, offline planning, and convenience tag generation' { + It 'supports offline -WhatIf -PassThru planning without invoking Docker or Git' { + $plan = & $buildScript -EngineVersion '1.1.0' -BuildOnly -Platform 'linux/amd64' -WhatIf -PassThru + + $global:DocfxBuildTestState.DockerCalls.Count | Should -Be 0 + $plan.DocfxVersion | Should -Be '2.81.0' + $plan.EngineVersion | Should -Be '1.1.0' + $plan.Repository | Should -Be 'codebeltnet/docfx' + $plan.EngineQualifiedTags | Should -Be @( + 'codebeltnet/docfx:2.81.0-v1.1.0' + 'codebeltnet/docfx:2.81-v1.1.0' + 'codebeltnet/docfx:2-v1.1.0' + ) + $plan.ConvenienceTags | Should -Be @( + 'codebeltnet/docfx:2.81.0' + 'codebeltnet/docfx:2.81' + 'codebeltnet/docfx:2' + 'codebeltnet/docfx:latest' + ) + + $silent = & $buildScript -Tag docfx-local -WhatIf + $silent | Should -BeNullOrEmpty + } + + It 'preserves existing convenience tags when EngineVersion is omitted locally' { + $plan = & $buildScript -Tag docfx-local -PassThru + + $global:DocfxBuildTestState.DockerCalls.Count | Should -Be 1 + $buildArgs = $global:DocfxBuildTestState.DockerCalls[0] + $tags = Get-ArgumentValues $buildArgs '--tag' + $labels = Get-ArgumentValues $buildArgs '--label' + + $tags | Should -Be @('docfx-local:2.81.0', 'docfx-local:2.81', 'docfx-local:2', 'docfx-local:latest') + $buildArgs | Should -Contain '--load' + $buildArgs | Should -Not -Contain '--push' + $labels | Should -Contain 'net.codebelt.docfx.cli.version=2.81.0' + $labels | Should -Contain "org.opencontainers.image.revision=$validRevision" + ($labels | Where-Object { $_ -like 'org.opencontainers.image.version=*' }) | Should -BeNullOrEmpty + ($labels | Where-Object { $_ -like 'net.codebelt.docfx.engine.version=*' }) | Should -BeNullOrEmpty + $plan.EngineVersion | Should -BeNullOrEmpty + } + + It 'builds all seven convenience and engine-qualified tags locally when EngineVersion is supplied' { + & $buildScript -Tag docfx-local -EngineVersion 1.1.0 -Platform linux/amd64 ` + -FrameworkSdkImage 'example.invalid/sdk:11-amd64' ` + -FrameworkSdkArm64Image 'example.invalid/sdk:11-arm64' + + $global:DocfxBuildTestState.DockerCalls.Count | Should -Be 1 + $buildArgs = $global:DocfxBuildTestState.DockerCalls[0] + $tags = Get-ArgumentValues $buildArgs '--tag' + $labels = Get-ArgumentValues $buildArgs '--label' + $buildArgValues = Get-ArgumentValues $buildArgs '--build-arg' + + $tags | Should -Be @( + 'docfx-local:2.81.0-v1.1.0' + 'docfx-local:2.81-v1.1.0' + 'docfx-local:2-v1.1.0' + 'docfx-local:2.81.0' + 'docfx-local:2.81' + 'docfx-local:2' + 'docfx-local:latest' + ) + $labels | Should -Contain 'org.opencontainers.image.version=1.1.0' + $labels | Should -Contain 'net.codebelt.docfx.engine.version=1.1.0' + $labels | Should -Contain 'net.codebelt.docfx.cli.version=2.81.0' + $labels | Should -Contain "org.opencontainers.image.revision=$validRevision" + $buildArgValues | Should -Contain 'DOCFX_VERSION=2.81.0' + $buildArgValues | Should -Contain 'DOTNET_VERSION=10.0' + $buildArgValues | Should -Contain 'FRAMEWORK_SDK_IMAGE=example.invalid/sdk:11-amd64' + $buildArgValues | Should -Contain 'FRAMEWORK_SDK_ARM64_IMAGE=example.invalid/sdk:11-arm64' + (Get-ArgumentValues $buildArgs '--platform') | Should -Be @('linux/amd64') + } + + It 'allows local builds without a Git repository by omitting the revision label' { + $global:DocfxBuildTestState.GitState.ExitCode = 128 + $global:DocfxBuildTestState.GitState.Output = 'fatal: not a git repository' + + & $buildScript -Tag docfx-local -EngineVersion 1.1.0 + + $labels = Get-ArgumentValues $global:DocfxBuildTestState.DockerCalls[0] '--label' + ($labels | Where-Object { $_ -like 'org.opencontainers.image.revision=*' }) | Should -BeNullOrEmpty + } + + It 'fails when docker buildx build exits non-zero' { + $global:DocfxBuildTestState.DockerState.BuildExitCode = 42 + { & $buildScript -Tag docfx-local } | Should -Throw '*exited with code 42*' + } + } + + Context 'Build-once OCI export and native validation mode (-BuildOnly)' { + It 'rejects combining -BuildOnly and -Publish or omitting -EngineVersion' { + { & $buildScript -BuildOnly -Publish -EngineVersion '1.1.0' } | Should -Throw '*Cannot combine -BuildOnly and -Publish*' + { & $buildScript -BuildOnly } | Should -Throw '*Build-only OCI export requires an explicit -EngineVersion*' + } + + It 'exports OCI archive with SBOM/provenance, verifies, loads via Skopeo, verifies config, and writes metadata' { + Mock Test-SkopeoTransport { return $true } + Mock Invoke-Skopeo { + param([string[]] $Arguments) + $global:DocfxBuildTestState.SkopeoCalls.Add($Arguments) + if ($Arguments[-1] -match '^docker-archive:(.+\.tar):') { + Set-Content -LiteralPath $Matches[1] -Value 'docker-tar' + } + } + Mock Invoke-OciArtifact { + param([string[]] $Arguments) + $global:DocfxBuildTestState.OciCalls.Add($Arguments) + if ($Arguments[0] -ceq 'verify') { + return (@{ indexDigest = $validIndexDigest; archiveSha256 = ('e' * 64); platforms = @('amd64'); configs = @{ amd64 = 'sha256:' + ('5' * 64) } } | ConvertTo-Json -Compress) + } + return 'sha256:' + ('5' * 64) + } + + $tempOut = Join-Path $TestDrive 'oci-build' + $archivePath = Join-Path $tempOut 'docfx.amd64.oci.tar' + $metadataPath = Join-Path $tempOut 'docfx-image.json' + + $record = & $buildScript -BuildOnly -EngineVersion '1.1.0' -Platform 'linux/amd64' -RequireNative -SkipContainerTest ` + -ArchivePath $archivePath -MetadataFile $metadataPath -PassThru + + $record.DocfxVersion | Should -Be '2.81.0' + $record.EngineVersion | Should -Be '1.1.0' + $record.Platform | Should -Be 'linux/amd64' + $record.ConfigDigest | Should -Be ('sha256:' + ('5' * 64)) + $record.NativeVerified | Should -BeFalse + Test-Path -LiteralPath $metadataPath | Should -BeTrue + $global:DocfxBuildTestState.SkopeoCalls.Count | Should -Be 1 + $global:DocfxBuildTestState.OciCalls.Count | Should -Be 2 + + $buildCall = @($global:DocfxBuildTestState.DockerCalls | Where-Object { $_[0] -ceq 'buildx' -and $_[1] -ceq 'build' })[0] + $buildCall | Should -Contain '--sbom=true' + $buildCall | Should -Contain '--provenance=mode=max' + + $nullOut = & $buildScript -BuildOnly -EngineVersion '1.1.0' -SkipContainerTest -ContainerRegistry '' -Tag 'docfx' ` + -ArchivePath (Join-Path $tempOut 'docfx-default.oci.tar') -MetadataFile (Join-Path $tempOut 'docfx-default.json') + $nullOut | Should -BeNullOrEmpty + } + + It 'invokes tests/Test-DocfxContainer.ps1 when -SkipContainerTest is not set' { + Mock Test-SkopeoTransport { return $true } + Mock Invoke-Skopeo { + param([string[]] $Arguments) + if ($Arguments[-1] -match '^docker-archive:(.+\.tar):') { + Set-Content -LiteralPath $Matches[1] -Value 'docker-tar' + } + } + Mock Invoke-OciArtifact { + param([string[]] $Arguments) + if ($Arguments[0] -ceq 'verify') { + return (@{ indexDigest = $validIndexDigest; archiveSha256 = ('e' * 64); platforms = @('amd64'); configs = @{ amd64 = 'sha256:' + ('5' * 64) } } | ConvertTo-Json -Compress) + } + return 'sha256:' + ('5' * 64) + } + + $tempOut = Join-Path $TestDrive 'oci-build-verify' + function global:docker { $global:LASTEXITCODE = 99; 'sentinel-container-test-invoked' } + try { + { & $buildScript -BuildOnly -EngineVersion '1.1.0' -Platform 'linux/amd64' ` + -ArchivePath (Join-Path $tempOut 'docfx.oci.tar') -MetadataFile (Join-Path $tempOut 'docfx.json') } | + Should -Throw '*sentinel-container-test-invoked*' + } finally { + Remove-Item Function:global:docker -ErrorAction SilentlyContinue + } + } + } + + Context 'Independent versions, future releases, and prerelease handling' { + It 'generates independent tags for ' -ForEach @( + @{ + CaseName = 'engine patch bump with same CLI' + Docfx = '2.81.0' + Engine = '1.1.1' + Expected = @('docfx:2.81.0-v1.1.1', 'docfx:2.81-v1.1.1', 'docfx:2-v1.1.1', 'docfx:2.81.0', 'docfx:2.81', 'docfx:2', 'docfx:latest') + } + @{ + CaseName = 'future major CLI and engine versions' + Docfx = '3.0.0' + Engine = '2.0.0' + Expected = @('docfx:3.0.0-v2.0.0', 'docfx:3.0-v2.0.0', 'docfx:3-v2.0.0', 'docfx:3.0.0', 'docfx:3.0', 'docfx:3', 'docfx:latest') + } + @{ + CaseName = 'prerelease engine does not move floating convenience tags' + Docfx = '2.81.0' + Engine = '1.2.0-rc.1' + Expected = @('docfx:2.81.0-v1.2.0-rc.1', 'docfx:2.81-v1.2.0-rc.1', 'docfx:2-v1.2.0-rc.1') + } + @{ + CaseName = 'prerelease CLI with stable engine emits only exact CLI tags' + Docfx = '2.82.0-preview.1' + Engine = '1.2.0' + Expected = @('docfx:2.82.0-preview.1-v1.2.0', 'docfx:2.82.0-preview.1') + } + @{ + CaseName = 'prerelease CLI with prerelease engine emits only exact combined tag' + Docfx = '2.82.0-preview.1' + Engine = '1.2.0-alpha.0a' + Expected = @('docfx:2.82.0-preview.1-v1.2.0-alpha.0a') + } + ) { + & $buildScript -DocfxVersion $Docfx -EngineVersion $Engine + $tags = Get-ArgumentValues $global:DocfxBuildTestState.DockerCalls[0] '--tag' + $tags | Should -Be $Expected + } + + It 'emits only exact prerelease CLI tag locally when EngineVersion is omitted' { + & $buildScript -DocfxVersion '2.82.0-preview.1' -Tag docfx-local + $tags = Get-ArgumentValues $global:DocfxBuildTestState.DockerCalls[0] '--tag' + $tags | Should -Be @('docfx-local:2.82.0-preview.1') + } + } + + Context 'Semantic Versioning and Docker tag validation' { + It 'rejects invalid EngineVersion ' -ForEach @( + @{ Version = ''; Expected = '*must not be empty*' } + @{ Version = ' '; Expected = '*must not be empty*' } + @{ Version = 'v1.1.0'; Expected = "*without a leading 'v'*" } + @{ Version = '1.1.0+build.1'; Expected = '*build metadata*' } + @{ Version = '01.1.0'; Expected = '*valid Semantic Version*' } + @{ Version = '1.1'; Expected = '*valid Semantic Version*' } + @{ Version = '1.1.0-01'; Expected = '*valid Semantic Version*' } + @{ Version = 'latest'; Expected = '*valid Semantic Version*' } + ) { + { & $buildScript -EngineVersion $Version } | Should -Throw $Expected + $global:DocfxBuildTestState.DockerCalls.Count | Should -Be 0 + } + + It 'rejects invalid DocfxVersion ' -ForEach @( + @{ Version = ''; Expected = '*DocfxVersion must not be empty*' } + @{ Version = 'v2.81.0'; Expected = "*without a leading 'v'*" } + @{ Version = '2.81.0+sha.abc'; Expected = '*build metadata*' } + @{ Version = '2.81'; Expected = '*valid Semantic Version*' } + ) { + { & $buildScript -DocfxVersion $Version } | Should -Throw $Expected + $global:DocfxBuildTestState.DockerCalls.Count | Should -Be 0 + } + + It 'rejects combined tags exceeding 128 characters or conflicting convenience tags' { + $longCli = '2.81.0-' + ('a' * 116) + { & $buildScript -DocfxVersion $longCli -EngineVersion '1.1.0' } | Should -Throw '*violates Docker tag constraints*maximum 128*' + { & $buildScript -DocfxVersion '2.81.0-v1.1.0' -EngineVersion '1.1.0' } | Should -Throw '*conflicts with the engine-qualified*' + } + + It 'rejects invalid Docker repository names' { + { & $buildScript -Tag 'Docfx' } | Should -Throw '*Invalid Docker repository*' + { & $buildScript -Tag 'docfx' -ContainerRegistry 'INVALID/REG' -EngineVersion '1.1.0' -Publish } | Should -Throw '*Invalid Docker repository*' + } + } + + Context 'Publication safeguards, official production protection, and custom registry verification' { + It 'refuses direct -Publish to official codebeltnet/docfx production repository' { + { & $buildScript -EngineVersion '1.1.0' -Publish } | Should -Throw '*Direct publication to official repository*disabled*build-once promotion*' + { & $buildScript -ContainerRegistry 'docker.io/codebeltnet/' -EngineVersion '1.1.0' -Publish } | Should -Throw '*Direct publication to official repository*disabled*' + $global:DocfxBuildTestState.DockerCalls.Count | Should -Be 0 + } + + It 'requires an explicit EngineVersion and valid platforms and Git revision when publishing to custom registries' { + { & $buildScript -ContainerRegistry 'localhost:5000/team/' -Publish } | Should -Throw '*Publishing requires an explicit -EngineVersion*' + { & $buildScript -Platform 'linux/386' } | Should -Throw '*Supported builder platforms are linux/amd64 and linux/arm64*' + { & $buildScript -Platform 'linux/amd64,linux/arm64' } | Should -Throw '*builds one platform at a time*' + { & $buildScript -ContainerRegistry 'localhost:5000/team/' -EngineVersion '1.1.0' -Platform 'linux/amd64' -Publish } | Should -Throw "*Specify exactly one platform for 'linux/arm64'*" + + $global:DocfxBuildTestState.GitState.ExitCode = 128 + $global:DocfxBuildTestState.GitState.Output = 'fatal: not a git repository' + { & $buildScript -ContainerRegistry 'localhost:5000/team/' -EngineVersion '1.1.0' -Publish } | Should -Throw '*valid Git source revision*' + } + + It 'refuses to reassign an already published engine-qualified tag on a custom registry' { + $global:DocfxBuildTestState.DockerState.PreflightResponses['localhost:5000/team/docfx:2.81-v1.1.0'] = @{ + ExitCode = 0 + Output = '{"digest":"sha256:' + ('9' * 64) + '"}' + } + + { & $buildScript -ContainerRegistry 'localhost:5000/team/' -EngineVersion '1.1.0' -Publish } | + Should -Throw "*localhost:5000/team/docfx:2.81-v1.1.0*already exists*Refusing to reassign*" + + $global:DocfxBuildTestState.DockerState.PreflightResponses['localhost:5000/team/docfx:2.81.0-v1.1.0'] = @{ + ExitCode = 0 + Output = '{}' + } + { & $buildScript -ContainerRegistry 'localhost:5000/team/' -EngineVersion '1.1.0' -Publish } | + Should -Throw '*already exists in the registry. Refusing to reassign*' + } + + It 'fails closed on unexpected registry errors during preflight' { + $global:DocfxBuildTestState.DockerState.PreflightResponses['localhost:5000/team/docfx:2.81.0-v1.1.0'] = @{ + ExitCode = 1 + Output = 'ERROR: unauthorized: authentication required' + } + + { & $buildScript -ContainerRegistry 'localhost:5000/team/' -EngineVersion '1.1.0' -Publish } | + Should -Throw '*Could not verify whether engine-qualified tag*unauthorized*' + } + + It 'publishes once to a custom registry, checks all seven tags, verifies both platforms and OCI labels' { + $output = & $buildScript -ContainerRegistry 'localhost:5000/team/' -EngineVersion '1.1.0' -Publish + $output | Should -BeExactly "localhost:5000/team/docfx:2.81.0-v1.1.0@$validIndexDigest" + + $global:DocfxBuildTestState.DockerState.HasPushed = $false + $global:DocfxBuildTestState.DockerState.IndexMediaType = 'application/vnd.docker.distribution.manifest.list.v2+json' + $output2 = & $buildScript -ContainerRegistry '' -Tag 'docfx' -EngineVersion '1.1.0' -Publish + $output2 | Should -BeExactly "docfx:2.81.0-v1.1.0@$validIndexDigest" + } + + It 'diagnoses post-publish verification failures on custom registries for ' -ForEach @( + @{ + Scenario = 'invalid buildx metadata digest' + Setup = { $global:DocfxBuildTestState.DockerState.BuildDigest = 'not-a-digest' } + Expected = '*valid published image digest*' + } + @{ + Scenario = 'tag resolving to a different index digest' + Setup = { $global:DocfxBuildTestState.DockerState.IndexDigest = 'sha256:' + ('f' * 64) } + Expected = '*does not resolve to image index*' + } + @{ + Scenario = 'tag resolving to a non-index mediaType' + Setup = { $global:DocfxBuildTestState.DockerState.IndexMediaType = 'application/vnd.oci.image.manifest.v1+json' } + Expected = '*does not resolve to image index*' + } + @{ + Scenario = 'missing platform manifest in image index' + Setup = { $global:DocfxBuildTestState.DockerState.Manifests = @($global:DocfxBuildTestState.DockerState.Manifests | Where-Object { $_.platform.architecture -cne 'arm64' }) } + Expected = "*does not identify one image manifest for 'linux/arm64'*" + } + @{ + Scenario = 'mismatched platform OS/architecture in image config' + Setup = { + $global:DocfxBuildTestState.DockerState.ImageResponses["localhost:5000/team/docfx@$arm64Digest"] = @{ + ExitCode = 0 + Output = (@{ os = 'linux'; architecture = 'amd64'; config = @{ Labels = $global:DocfxBuildTestState.DockerState.ImageLabels } } | ConvertTo-Json -Depth 5) + } + } + Expected = "*Published image config for 'linux/arm64' reports 'linux/amd64'*" + } + @{ + Scenario = 'mismatched OCI engine version label' + Setup = { $global:DocfxBuildTestState.DockerState.ImageLabels['org.opencontainers.image.version'] = '1.0.1' } + Expected = "*reports label 'org.opencontainers.image.version' as '1.0.1' instead of '1.1.0'*" + } + @{ + Scenario = 'missing OCI labels object' + Setup = { $global:DocfxBuildTestState.DockerState.ImageLabels = $null } + Expected = "*reports label 'org.opencontainers.image.version' as '' instead of '1.1.0'*" + } + ) { + & $Setup + { & $buildScript -ContainerRegistry 'localhost:5000/team/' -EngineVersion '1.1.0' -Publish } | Should -Throw $Expected + } + } +} diff --git a/tests/OciArtifact.Tests.ps1 b/tests/OciArtifact.Tests.ps1 new file mode 100644 index 0000000..de26ef0 --- /dev/null +++ b/tests/OciArtifact.Tests.ps1 @@ -0,0 +1,382 @@ +BeforeAll { + $repoRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path + $ociTool = Join-Path $repoRoot 'tools/OciArtifact.cs' + $validRevision = 'a' * 40 + $validVersion = '1.1.0' + $validDocfx = '2.81.0' + $defaultSource = 'https://github.com/codebeltnet/docfx' + + function Invoke-OciTool { + param([string[]] $Arguments) + $output = & dotnet run --file $ociTool -- @Arguments 2>&1 + [pscustomobject]@{ + ExitCode = $LASTEXITCODE + Output = (@($output | ForEach-Object { $_.ToString() }) -join "`n").Trim() + } + } + + function New-SyntheticOciArchive { + param( + [Parameter(Mandatory)][string] $Path, + [Parameter(Mandatory)][string] $Cpu, + [string] $Version = $validVersion, + [string] $DocfxVersion = $validDocfx, + [string] $Revision = $validRevision, + [string] $Source = $defaultSource, + [string] $Created = '2026-11-25T12:00:00Z', + [string] $MissingPredicate, + [string] $SubjectOverride, + [switch] $EmptySubject, + [string] $ProvenanceDocfxVersion, + [switch] $UseSlsaV1, + [switch] $WrapLayoutIndex, + [switch] $ExtraWindowsPlatform, + [switch] $EmptySbom, + [switch] $Seal + ) + + $blobs = [ordered]@{} + function Add-JsonBlob([hashtable] $Obj, [string] $MediaType = 'application/vnd.oci.image.manifest.v1+json') { + $json = ConvertTo-Json -InputObject $Obj -Depth 20 -Compress + $bytes = [Text.UTF8Encoding]::new($false).GetBytes($json) + $hex = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($bytes)).ToLowerInvariant() + $blobs["blobs/sha256/$hex"] = $bytes + @{ digest = "sha256:$hex"; size = $bytes.Length; mediaType = $MediaType } + } + + $layerBytes = [Text.UTF8Encoding]::new($false).GetBytes("synthetic-layer-$Cpu") + $layerHex = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($layerBytes)).ToLowerInvariant() + $blobs["blobs/sha256/$layerHex"] = $layerBytes + $layerDesc = @{ digest = "sha256:$layerHex"; size = $layerBytes.Length; mediaType = 'application/vnd.oci.image.layer.v1.tar+gzip' } + + $labels = [ordered]@{ + 'org.opencontainers.image.source' = $Source + 'org.opencontainers.image.version' = $Version + 'org.opencontainers.image.revision' = $Revision + 'net.codebelt.docfx.engine.version' = $Version + 'net.codebelt.docfx.cli.version' = $DocfxVersion + } + if ($Created) { $labels['org.opencontainers.image.created'] = $Created } + + $configDesc = Add-JsonBlob @{ + architecture = $Cpu + os = 'linux' + config = @{ Labels = $labels } + } 'application/vnd.oci.image.config.v1+json' + + $imageDesc = Add-JsonBlob @{ + schemaVersion = 2 + mediaType = 'application/vnd.oci.image.manifest.v1+json' + config = $configDesc + layers = @($layerDesc) + } + $imageDesc['platform'] = @{ os = 'linux'; architecture = $Cpu } + + $attLayers = [System.Collections.Generic.List[hashtable]]::new() + $provDocfx = if ($ProvenanceDocfxVersion) { $ProvenanceDocfxVersion } else { $DocfxVersion } + $provArgs = @{ + 'build-arg:DOCFX_VERSION' = $provDocfx + 'label:org.opencontainers.image.version' = $Version + 'label:net.codebelt.docfx.engine.version' = $Version + 'label:net.codebelt.docfx.cli.version' = $DocfxVersion + 'label:org.opencontainers.image.revision' = $Revision + 'label:org.opencontainers.image.source' = $Source + } + $slsaPredicate = if ($UseSlsaV1) { + @{ + predicateType = 'https://slsa.dev/provenance/v1' + body = @{ + buildDefinition = @{ + buildType = 'https://mobyproject.org/buildkit@v1' + externalParameters = @{ request = @{ args = $provArgs } } + } + } + } + } else { + @{ + predicateType = 'https://slsa.dev/provenance/v0.2' + body = @{ + buildType = 'https://mobyproject.org/buildkit@v1' + invocation = @{ parameters = @{ args = $provArgs } } + } + } + } + $sbomPackages = [System.Collections.Generic.List[hashtable]]::new() + if (-not $EmptySbom) { $sbomPackages.Add(@{ name = 'docfx' }) } + $sbomBody = @{ spdxVersion = 'SPDX-2.3'; packages = @($sbomPackages.ToArray()) } + + foreach ($entry in @( + @{ predicateType = 'https://spdx.dev/Document'; body = $sbomBody } + $slsaPredicate + )) { + if ($entry.predicateType -ceq $MissingPredicate) { continue } + $subjects = [System.Collections.Generic.List[hashtable]]::new() + if (-not $EmptySubject) { + $subjHex = if ($SubjectOverride) { $SubjectOverride } else { $imageDesc.digest.Substring(7) } + $subjects.Add(@{ digest = @{ sha256 = $subjHex } }) + } + $attLayers.Add((Add-JsonBlob @{ + predicateType = $entry.predicateType + predicate = $entry.body + subject = @($subjects.ToArray()) + } 'application/vnd.in-toto+json')) + } + + $attDesc = Add-JsonBlob @{ + schemaVersion = 2 + mediaType = 'application/vnd.oci.image.manifest.v1+json' + layers = @($attLayers.ToArray()) + } + $attDesc['platform'] = @{ os = 'unknown'; architecture = 'unknown' } + $attDesc['annotations'] = @{ + 'vnd.docker.reference.digest' = $imageDesc.digest + 'vnd.docker.reference.type' = 'attestation-manifest' + } + + $manifests = [System.Collections.Generic.List[hashtable]]::new() + $manifests.Add($imageDesc) + $manifests.Add($attDesc) + if ($ExtraWindowsPlatform) { + $manifests.Add(@{ + mediaType = 'application/vnd.oci.image.manifest.v1+json' + digest = $imageDesc.digest + size = $imageDesc.size + platform = @{ os = 'windows'; architecture = 'amd64' } + }) + } + + $indexObj = @{ + schemaVersion = 2 + mediaType = 'application/vnd.oci.image.index.v1+json' + manifests = @($manifests.ToArray()) + } + + if ($WrapLayoutIndex) { + $wrappedDesc = Add-JsonBlob $indexObj 'application/vnd.oci.image.index.v1+json' + $wrappedDesc['annotations'] = @{ 'org.opencontainers.image.ref.name' = $Version } + $rootIndexObj = @{ + schemaVersion = 2 + mediaType = 'application/vnd.oci.image.index.v1+json' + manifests = @($wrappedDesc) + } + } else { + $rootIndexObj = $indexObj + } + + $indexBytes = [Text.UTF8Encoding]::new($false).GetBytes((ConvertTo-Json -InputObject $rootIndexObj -Depth 20 -Compress)) + $layoutBytes = [Text.UTF8Encoding]::new($false).GetBytes('{"imageLayoutVersion":"1.0.0"}') + + $dir = Split-Path -Parent $Path + if ($dir) { New-Item -ItemType Directory -Path $dir -Force | Out-Null } + $fs = [IO.File]::Create($Path) + try { + $writer = [System.Formats.Tar.TarWriter]::new($fs, [System.Formats.Tar.TarEntryFormat]::Pax, $false) + try { + foreach ($name in $blobs.Keys) { + $ms = [IO.MemoryStream]::new($blobs[$name], $false) + try { + $tarEntry = [System.Formats.Tar.PaxTarEntry]::new([System.Formats.Tar.TarEntryType]::RegularFile, $name) + $tarEntry.DataStream = $ms + $writer.WriteEntry($tarEntry) + } finally { $ms.Dispose() } + } + foreach ($metaEntry in @( + @{ name = 'index.json'; bytes = $indexBytes } + @{ name = 'oci-layout'; bytes = $layoutBytes } + )) { + $ms = [IO.MemoryStream]::new($metaEntry.bytes, $false) + try { + $tarEntry = [System.Formats.Tar.PaxTarEntry]::new([System.Formats.Tar.TarEntryType]::RegularFile, $metaEntry.name) + $tarEntry.DataStream = $ms + $writer.WriteEntry($tarEntry) + } finally { $ms.Dispose() } + } + } finally { $writer.Dispose() } + } finally { $fs.Dispose() } + + if ($Seal) { + $hash = (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() + "$hash $(Split-Path -Leaf $Path)`n" | Set-Content -LiteralPath "$Path.sha256" -NoNewline -Encoding utf8NoBOM + } + + [pscustomobject]@{ + Path = $Path + ImageDigest = $imageDesc.digest + ConfigDigest = $configDesc.digest + } + } +} + +Describe 'OciArtifact .NET 10 file-based OCI tooling' { + BeforeEach { + $workDir = Join-Path ([IO.Path]::GetTempPath()) ('docfx-oci-test-' + [guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $workDir -Force | Out-Null + } + + AfterEach { + if (Test-Path -LiteralPath $workDir) { + Remove-Item -LiteralPath $workDir -Recurse -Force + } + } + + Context 'Verification of OCI archives, labels, blobs, and attestations' { + It 'verifies a valid single-platform OCI archive with SLSA v0.2 and writes detached checksum' { + $fixture = New-SyntheticOciArchive -Path (Join-Path $workDir 'amd64.oci.tar') -Cpu amd64 -WrapLayoutIndex + $res = Invoke-OciTool @('verify', $fixture.Path, '--version', $validVersion, '--docfx-version', $validDocfx, '--revision', $validRevision, '--platform', 'amd64') + + $res.ExitCode | Should -Be 0 + $json = $res.Output | ConvertFrom-Json + $json.platforms | Should -Be @('amd64') + $json.configs.amd64 | Should -Be $fixture.ConfigDigest + Test-Path -LiteralPath "$($fixture.Path).sha256" | Should -BeTrue + } + + It 'verifies SLSA v1.0 provenance and custom fork source repository' { + $forkSource = 'https://github.com/fork-owner/docfx' + $fixture = New-SyntheticOciArchive -Path (Join-Path $workDir 'arm64.oci.tar') -Cpu arm64 -Source $forkSource -UseSlsaV1 + $res = Invoke-OciTool @('verify', $fixture.Path, '--version', $validVersion, '--docfx-version', $validDocfx, '--revision', $validRevision, '--source', $forkSource, '--platform', 'arm64') + + $res.ExitCode | Should -Be 0 + ($res.Output | ConvertFrom-Json).configs.arm64 | Should -Be $fixture.ConfigDigest + } + + It 'rejects platform mismatch, missing attestations, subject mismatch, and label drift' -ForEach @( + @{ Name = 'wrong CPU platform'; Params = @{ Cpu = 'amd64' }; Platform = 'arm64'; Expected = '*Unexpected platform inventory*' } + @{ Name = 'extra untested runtime platform'; Params = @{ Cpu = 'amd64'; ExtraWindowsPlatform = $true }; Platform = 'amd64'; Expected = '*Unexpected runtime*' } + @{ Name = 'missing SPDX SBOM'; Params = @{ Cpu = 'amd64'; MissingPredicate = 'https://spdx.dev/Document' }; Platform = 'amd64'; Expected = '*SBOM or provenance missing*' } + @{ Name = 'empty SPDX SBOM'; Params = @{ Cpu = 'amd64'; EmptySbom = $true }; Platform = 'amd64'; Expected = '*Empty SBOM*' } + @{ Name = 'missing SLSA provenance'; Params = @{ Cpu = 'amd64'; MissingPredicate = 'https://slsa.dev/provenance/v0.2' }; Platform = 'amd64'; Expected = '*SBOM or provenance missing*' } + @{ Name = 'wrong attestation subject'; Params = @{ Cpu = 'amd64'; SubjectOverride = ('c' * 64) }; Platform = 'amd64'; Expected = '*Attestation subject mismatch*' } + @{ Name = 'empty attestation subject'; Params = @{ Cpu = 'amd64'; EmptySubject = $true }; Platform = 'amd64'; Expected = '*Attestation subject mismatch*' } + @{ Name = 'wrong engine version label'; Params = @{ Cpu = 'amd64'; Version = '1.0.9' }; Platform = 'amd64'; Expected = '*Identity mismatch*' } + @{ Name = 'wrong DocFX CLI version label'; Params = @{ Cpu = 'amd64'; DocfxVersion = '2.80.0' }; Platform = 'amd64'; Expected = '*Identity mismatch*' } + @{ Name = 'wrong provenance build-arg DOCFX_VERSION'; Params = @{ Cpu = 'amd64'; ProvenanceDocfxVersion = '2.80.0' }; Platform = 'amd64'; Expected = '*Provenance build identity mismatch*' } + @{ Name = 'missing created timestamp label'; Params = @{ Cpu = 'amd64'; Created = '' }; Platform = 'amd64'; Expected = '*Missing build identity*' } + ) { + $path = Join-Path $workDir 'bad.oci.tar' + $null = New-SyntheticOciArchive -Path $path @Params + $res = Invoke-OciTool @('verify', $path, '--version', $validVersion, '--docfx-version', $validDocfx, '--revision', $validRevision, '--platform', $Platform, '--no-seal') + + $res.ExitCode | Should -Not -Be 0 + $res.Output | Should -BeLike $Expected + } + + It 'rejects a corrupted OCI blob even after resealing the archive checksum' { + $fixture = New-SyntheticOciArchive -Path (Join-Path $workDir 'corrupt.oci.tar') -Cpu amd64 -Seal + $bytes = [IO.File]::ReadAllBytes($fixture.Path) + $text = [Text.Encoding]::Latin1.GetString($bytes).Replace('synthetic-layer-amd64', 'tampered!-layer-amd64') + [IO.File]::WriteAllBytes($fixture.Path, [Text.Encoding]::Latin1.GetBytes($text)) + $null = Invoke-OciTool @('seal', $fixture.Path) + + $res = Invoke-OciTool @('verify', $fixture.Path, '--version', $validVersion, '--docfx-version', $validDocfx, '--revision', $validRevision, '--platform', 'amd64', '--check-seal', '--no-seal') + $res.ExitCode | Should -Not -Be 0 + $res.Output | Should -BeLike '*Corrupt OCI blob*' + } + + It 'rejects checksum tampering via check-seal' { + $fixture = New-SyntheticOciArchive -Path (Join-Path $workDir 'sealed.oci.tar') -Cpu amd64 -Seal + Add-Content -LiteralPath $fixture.Path -Value 'tamper' -NoNewline + + $res = Invoke-OciTool @('check-seal', $fixture.Path) + $res.ExitCode | Should -Not -Be 0 + $res.Output | Should -BeLike '*Archive checksum mismatch*' + } + } + + Context 'Multi-platform merge, splitting, reassembly, and layout extraction' { + It 'merges verified amd64 and arm64 archives preserving exact child configs and Codebelt verifier contract' { + $amd = New-SyntheticOciArchive -Path (Join-Path $workDir 'amd64.oci.tar') -Cpu amd64 -Seal + $arm = New-SyntheticOciArchive -Path (Join-Path $workDir 'arm64.oci.tar') -Cpu arm64 -Seal + $mergedPath = Join-Path $workDir 'merged.oci.tar' + + $res = Invoke-OciTool @( + 'merge', $mergedPath + '--version', $validVersion + '--docfx-version', $validDocfx + '--revision', $validRevision + '--input', $amd.Path + '--input', $arm.Path + ) + $res.ExitCode | Should -Be 0 + $merged = $res.Output | ConvertFrom-Json + $merged.indexDigest | Should -Match '^sha256:[0-9a-f]{64}$' + $merged.platforms | Should -Be @('amd64', 'arm64') + $merged.configs.amd64 | Should -Be $amd.ConfigDigest + $merged.configs.arm64 | Should -Be $arm.ConfigDigest + Test-Path -LiteralPath "$mergedPath.sha256" | Should -BeTrue + + # Extract layout and verify index.json conforms to codebeltnet/oci-artifact-verify contract + $layoutDir = Join-Path $workDir 'layout' + $extractRes = Invoke-OciTool @('extract-layout', $mergedPath, '--output-dir', $layoutDir) + $extractRes.ExitCode | Should -Be 0 + + $outerIndex = Get-Content -LiteralPath (Join-Path $layoutDir 'index.json') -Raw | ConvertFrom-Json + $outerIndex.manifests.Count | Should -Be 1 + $outerIndex.manifests[0].digest | Should -Be $merged.indexDigest + $outerIndex.manifests[0].annotations.'org.opencontainers.image.ref.name' | Should -Be $validVersion + + $embeddedHex = $merged.indexDigest.Substring(7) + $embeddedIndex = Get-Content -LiteralPath (Join-Path $layoutDir "blobs/sha256/$embeddedHex") -Raw | ConvertFrom-Json + $embeddedIndex.annotations.'org.opencontainers.image.version' | Should -Be $validVersion + $embeddedIndex.annotations.'org.opencontainers.image.revision' | Should -Be $validRevision + $embeddedIndex.annotations.'net.codebelt.docfx.cli.version' | Should -Be $validDocfx + } + + It 'rejects merge when a required platform is missing or duplicated' { + $amd = New-SyntheticOciArchive -Path (Join-Path $workDir 'amd64.oci.tar') -Cpu amd64 -Seal + $mergedPath = Join-Path $workDir 'incomplete.oci.tar' + + $missingArm = Invoke-OciTool @('merge', $mergedPath, '--version', $validVersion, '--docfx-version', $validDocfx, '--revision', $validRevision, '--input', $amd.Path) + $missingArm.ExitCode | Should -Not -Be 0 + $missingArm.Output | Should -BeLike '*Unexpected platform inventory*' + + $dupAmd = Invoke-OciTool @('merge', $mergedPath, '--version', $validVersion, '--docfx-version', $validDocfx, '--revision', $validRevision, '--input', $amd.Path, '--input', $amd.Path) + $dupAmd.ExitCode | Should -Not -Be 0 + $dupAmd.Output | Should -BeLike '*Duplicate input platform*' + } + + It 'splits an OCI archive into multiple parts and reconstructs byte-identical content' { + $amd = New-SyntheticOciArchive -Path (Join-Path $workDir 'amd64.oci.tar') -Cpu amd64 -Seal + $arm = New-SyntheticOciArchive -Path (Join-Path $workDir 'arm64.oci.tar') -Cpu arm64 -Seal + $mergedPath = Join-Path $workDir 'docfx.oci.tar' + $mergeRes = Invoke-OciTool @('merge', $mergedPath, '--version', $validVersion, '--docfx-version', $validDocfx, '--revision', $validRevision, '--input', $amd.Path, '--input', $arm.Path) + $mergeRes.ExitCode | Should -Be 0 + $originalSha = (Get-FileHash -LiteralPath $mergedPath -Algorithm SHA256).Hash.ToLowerInvariant() + + $partsDir = Join-Path $workDir 'parts' + $splitRes = Invoke-OciTool @('split', $mergedPath, '--output-dir', $partsDir, '--prefix', 'docfx', '--part-size', '2048', '--write-checksum') + $splitRes.ExitCode | Should -Be 0 + $splitData = $splitRes.Output | ConvertFrom-Json + $splitData.pieces.Count | Should -BeGreaterThan 1 + $splitData.archiveSha256 | Should -Be $originalSha + + $manifestPath = Join-Path $workDir 'release.json' + @{ + ArchiveSha256 = $splitData.archiveSha256 + ArchiveBytes = $splitData.archiveBytes + Pieces = @($splitData.pieces | ForEach-Object { @{ Name = $_.name; Sha256 = $_.sha256; Size = $_.size } }) + } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath + + $rebuiltPath = Join-Path $workDir 'rebuilt/docfx.oci.tar' + $reassembleRes = Invoke-OciTool @( + 'reassemble' + '--manifest', $manifestPath + '--input-dir', $partsDir + '--output', $rebuiltPath + '--checksum', (Join-Path $partsDir 'docfx.oci.tar.sha256') + ) + $reassembleRes.ExitCode | Should -Be 0 + (Get-FileHash -LiteralPath $rebuiltPath -Algorithm SHA256).Hash.ToLowerInvariant() | Should -Be $originalSha + + # Verify tampered piece is rejected during reconstruction + $firstPart = Join-Path $partsDir $splitData.pieces[0].name + $partBytes = [IO.File]::ReadAllBytes($firstPart) + $partBytes[0] = $partBytes[0] -bxor 0xFF + [IO.File]::WriteAllBytes($firstPart, $partBytes) + + $tamperedRes = Invoke-OciTool @('reassemble', '--manifest', $manifestPath, '--input-dir', $partsDir, '--output', (Join-Path $workDir 'rebuilt2/docfx.oci.tar')) + $tamperedRes.ExitCode | Should -Not -Be 0 + $tamperedRes.Output | Should -BeLike '*differs from verified release record*' + } + } +} diff --git a/tests/ReleaseDelivery.Tests.ps1 b/tests/ReleaseDelivery.Tests.ps1 new file mode 100644 index 0000000..057f94b --- /dev/null +++ b/tests/ReleaseDelivery.Tests.ps1 @@ -0,0 +1,807 @@ +BeforeAll { + $repoRoot = (Resolve-Path -LiteralPath "$PSScriptRoot/..").Path + $modulePath = (Resolve-Path -LiteralPath "$PSScriptRoot/../tools/DocfxImage.psm1").Path + $releaseScript = (Resolve-Path -LiteralPath "$PSScriptRoot/../tools/Invoke-DocfxRelease.ps1").Path + Import-Module $modulePath -Force + + if (-not (Get-Command skopeo -ErrorAction SilentlyContinue)) { + function global:skopeo { $global:LASTEXITCODE = 0 } + $script:createdSkopeoStub = $true + } else { + $script:createdSkopeoStub = $false + } + + $validRevision = 'a' * 40 + $validIndexDigest = 'sha256:' + ('1' * 64) + $conflictDigest = 'sha256:' + ('9' * 64) + $amd64Config = 'sha256:' + ('2' * 64) + $arm64Config = 'sha256:' + ('3' * 64) + $validTags = @( + 'codebeltnet/docfx:2.81.0-v1.1.0' + 'codebeltnet/docfx:2.81-v1.1.0' + 'codebeltnet/docfx:2-v1.1.0' + 'codebeltnet/docfx:2.81.0' + 'codebeltnet/docfx:2.81' + 'codebeltnet/docfx:2' + 'codebeltnet/docfx:latest' + ) + $validEngineTags = $validTags[0..2] + $validConvenienceTags = $validTags[3..6] +} + +AfterAll { + if ($script:createdSkopeoStub) { + Remove-Item Function:global:skopeo -ErrorAction SilentlyContinue + } +} + +Describe 'DocfxImage shared module contracts and OCI promotion safeguards' { + Context 'Version resolution and repository consistency' { + It 'validates vMAJOR.MINOR.PATCH release tags and rejects invalid tags' { + Resolve-ReleaseTagVersion -Tag 'v1.1.0' | Should -Be '1.1.0' + foreach ($bad in @('', '1.1.0', 'v01.1.0', 'v1.1', 'v1.1.0-rc.1', 'latest')) { + { Resolve-ReleaseTagVersion -Tag $bad } | Should -Throw '*Invalid release tag*' + } + } + + It 'verifies repository DocFX version consistency and detects drift' { + Test-DocfxVersionConsistency -RootPath $repoRoot | Should -Be '2.81.0' + + $missingRoot = Join-Path $TestDrive 'missing-dockerfile' + New-Item -ItemType Directory -Path $missingRoot -Force | Out-Null + { Get-DocfxDefaultVersion -RootPath $missingRoot } | Should -Throw '*Authoritative Dockerfile was not found*' + + $driftRoot = Join-Path $TestDrive 'drift' + New-Item -ItemType Directory -Path "$driftRoot/framework-views", "$driftRoot/templates/ms-style" -Force | Out-Null + Set-Content -LiteralPath "$driftRoot/Dockerfile" 'FROM scratch' + { Get-DocfxDefaultVersion -RootPath $driftRoot } | Should -Throw '*Dockerfile does not declare*ARG DOCFX_VERSION*' + + Set-Content -LiteralPath "$driftRoot/Dockerfile" 'ARG DOCFX_VERSION=2.81.0' + Set-Content -LiteralPath "$driftRoot/framework-views/Build-DocfxFrameworkViews.ps1" '$supportedDocfx = ''2.80.0''' + Set-Content -LiteralPath "$driftRoot/templates/ms-style/framework-views.compat" 'framework-views-v1/docfx-2.81.0' + { Test-DocfxVersionConsistency -RootPath $driftRoot } | Should -Throw '*Build-DocfxFrameworkViews.ps1*' + + Set-Content -LiteralPath "$driftRoot/framework-views/Build-DocfxFrameworkViews.ps1" '$supportedDocfx = ''2.81.0''' + Set-Content -LiteralPath "$driftRoot/templates/ms-style/framework-views.compat" 'framework-views-v1/docfx-2.80.0' + { Test-DocfxVersionConsistency -RootPath $driftRoot } | Should -Throw '*framework-views.compat*' + } + } + + Context 'Native Docker host and Skopeo transport checks' { + It 'enforces native Docker host architecture without silent emulation' { + Mock -ModuleName DocfxImage docker { $global:LASTEXITCODE = 0; 'linux/x86_64' } + { Assert-NativeDockerHost -Platform 'linux/amd64' } | Should -Not -Throw + { Assert-NativeDockerHost -Platform 'linux/arm64' -DockerContext 'ctx' } | Should -Throw '*Native Docker host required*' + + Mock -ModuleName DocfxImage docker { $global:LASTEXITCODE = 1; 'daemon down' } + { Assert-NativeDockerHost -Platform 'linux/amd64' } | Should -Throw '*Cannot access native Docker host*' + } + + It 'selects native Skopeo or local utility container and rejects remote TCP/SSH daemons without native Skopeo' { + Mock -ModuleName DocfxImage Get-Command { [pscustomobject]@{ Source = '/usr/bin/skopeo' } } + Test-SkopeoTransport | Should -BeTrue + + $prevHost = $env:DOCKER_HOST + $prevCtx = $env:DOCKER_CONTEXT + try { + Mock -ModuleName DocfxImage Get-Command { $null } + $env:DOCKER_CONTEXT = '' + $env:DOCKER_HOST = 'unix:///var/run/docker.sock' + Test-SkopeoTransport | Should -BeFalse + + $env:DOCKER_HOST = 'ssh://remote-builder' + { Test-SkopeoTransport } | Should -Throw '*Native Skopeo is required*' + + $env:DOCKER_HOST = '' + Mock -ModuleName DocfxImage docker { $global:LASTEXITCODE = 0; 'npipe:////./pipe/docker_engine' } + Test-SkopeoTransport | Should -BeFalse + + $env:DOCKER_CONTEXT = 'local' + $env:DOCKER_HOST = 'ssh://ignored-when-context-set' + Test-SkopeoTransport | Should -BeFalse + $env:DOCKER_CONTEXT = '' + $env:DOCKER_HOST = '' + + Mock -ModuleName DocfxImage docker { $global:LASTEXITCODE = 1; 'inspect failed' } + { Test-SkopeoTransport } | Should -Throw '*Unable to inspect active Docker context*' + } finally { + $env:DOCKER_HOST = $prevHost + $env:DOCKER_CONTEXT = $prevCtx + } + } + + It 'invokes Skopeo natively and via utility container fallback with auth mount and error propagation' { + Mock -ModuleName DocfxImage Test-SkopeoTransport { $true } + Mock -ModuleName DocfxImage skopeo { $global:LASTEXITCODE = 0 } + { Invoke-Skopeo -Arguments @('copy', 'oci:/tmp/x', 'docker://reg/img:1') } | Should -Not -Throw + + Mock -ModuleName DocfxImage skopeo { $global:LASTEXITCODE = 7 } + { Invoke-Skopeo -Arguments @('copy', 'oci:/tmp/x', 'docker://reg/img:1') } | Should -Throw '*exited with code 7*' + + $global:DocfxPwshPath = (Get-Command pwsh).Source + Mock -ModuleName DocfxImage Get-Command { [pscustomobject]@{ Source = $global:DocfxPwshPath } } + $captured = Invoke-Skopeo -Arguments @('-NoProfile', '-Command', '[Console]::Out.Write("hello-raw")') -CaptureOutput + [Text.Encoding]::UTF8.GetString($captured) | Should -Be 'hello-raw' + + { Invoke-Skopeo -Arguments @('-NoProfile', '-Command', '[Console]::Error.Write("manifest unknown"); exit 1') -CaptureOutput } | + Should -Throw '*exited with code 1*manifest unknown*' + Remove-Variable DocfxPwshPath -Scope Global -ErrorAction SilentlyContinue + + $prevAuth = $env:REGISTRY_AUTH_FILE + $authFile = Join-Path $TestDrive 'auth.json' + Set-Content -LiteralPath $authFile '{}' + $global:DocfxCapturedDockerArgs = $null + try { + $env:REGISTRY_AUTH_FILE = $authFile + Mock -ModuleName DocfxImage Test-SkopeoTransport { $false } + Mock -ModuleName DocfxImage docker { + $global:DocfxCapturedDockerArgs = @($args) + $global:LASTEXITCODE = 0 + '{"schemaVersion":2}' + } + + $tarFile = Join-Path $TestDrive 'sample.tar' + Invoke-Skopeo -Arguments @('copy', "oci-archive:$tarFile", "docker-archive:${tarFile}:local:tag") + ($global:DocfxCapturedDockerArgs -join ' ') | Should -BeLike '*REGISTRY_AUTH_FILE=/auth.json*quay.io/skopeo/stable:v1.20.0*' + + $rawBytes = Invoke-Skopeo -Arguments @('inspect', '--raw', 'docker://reg/img:1') -CaptureOutput + [Text.Encoding]::UTF8.GetString($rawBytes) | Should -Be '{"schemaVersion":2}' + + Mock -ModuleName DocfxImage docker { $global:LASTEXITCODE = 1; 'unauthorized' } + { Invoke-Skopeo -Arguments @('inspect', '--raw', 'docker://reg/img:1') -CaptureOutput } | + Should -Throw '*exited with code 1*unauthorized*' + } finally { + $env:REGISTRY_AUTH_FILE = $prevAuth + Remove-Variable DocfxCapturedDockerArgs -Scope Global -ErrorAction SilentlyContinue + } + } + + It 'wraps Invoke-OciArtifact and handles non-zero failures cleanly' { + Mock -ModuleName DocfxImage dotnet { $global:LASTEXITCODE = 0; '{"ok":true}' } + (Invoke-OciArtifact -Arguments @('seal', 'a.tar')) | Should -Be '{"ok":true}' + + Mock -ModuleName DocfxImage dotnet { $global:LASTEXITCODE = 1; 'bad archive' } + { Invoke-OciArtifact -Arguments @('verify', 'a.tar') } | Should -Throw '*OciArtifact verify failed (exit 1): bad archive*' + } + + It 'distinguishes missing registry manifests from auth/network/server errors' { + $global:DocfxRawBytes = [Text.Encoding]::UTF8.GetBytes('{"schemaVersion":2}') + $expectedHash = 'sha256:' + [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($global:DocfxRawBytes)).ToLowerInvariant() + + try { + Mock -ModuleName DocfxImage Invoke-Skopeo { return $global:DocfxRawBytes } + Get-RegistryManifestDigest -Reference 'codebeltnet/docfx:2.81.0-v1.1.0' | Should -Be $expectedHash + + Mock -ModuleName DocfxImage Invoke-Skopeo { throw 'skopeo inspect exited with code 1: manifest unknown' } + Get-RegistryManifestDigest -Reference 'codebeltnet/docfx:2.81.0-v1.1.0' | Should -BeNullOrEmpty + + Mock -ModuleName DocfxImage Invoke-Skopeo { throw 'skopeo inspect exited with code 1: unauthorized: authentication required' } + { Get-RegistryManifestDigest -Reference 'codebeltnet/docfx:2.81.0-v1.1.0' } | Should -Throw '*Could not inspect registry reference*unauthorized*' + } finally { + Remove-Variable DocfxRawBytes -Scope Global -ErrorAction SilentlyContinue + } + } + } + + Context 'Promotion preflight, conflict prevention, idempotent retry, and stale protection' { + BeforeEach { + $archiveFile = Join-Path $TestDrive 'docfx.oci.tar' + Set-Content -LiteralPath $archiveFile 'archive-bytes' + $rawIndexBytes = [Text.Encoding]::UTF8.GetBytes('{"schemaVersion":2,"manifests":[]}') + $computedDigest = 'sha256:' + [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($rawIndexBytes)).ToLowerInvariant() + + $global:DocfxPromoState = @{ + ArchiveFile = $archiveFile + RawIndexBytes = $rawIndexBytes + ComputedDigest = $computedDigest + ConflictDigest = $conflictDigest + Amd64Config = $amd64Config + Arm64Config = $arm64Config + Registry = @{} + Events = [System.Collections.Generic.List[string]]::new() + CallNum = 0 + InspectCount = 0 + } + + Mock -ModuleName DocfxImage Invoke-OciArtifact { + param([string[]] $Arguments) + $s = $global:DocfxPromoState + switch ($Arguments[0]) { + 'check-seal' { '{"archiveSha256":"' + ('a' * 64) + '"}' } + 'verify' { (@{ indexDigest = $s.ComputedDigest; platforms = @('amd64', 'arm64'); configs = @{ amd64 = $s.Amd64Config; arm64 = $s.Arm64Config } } | ConvertTo-Json -Compress) } + 'extract-layout' { + $dir = $Arguments[3] + New-Item -ItemType Directory -Path $dir -Force | Out-Null + '{"layoutPath":"' + $dir.Replace('\', '\\') + '"}' + } + } + } + } + + AfterEach { + Remove-Variable DocfxPromoState -Scope Global -ErrorAction SilentlyContinue + } + + It 'rejects invalid tag sets in preflight' { + $base = @{ + ArchivePath = $global:DocfxPromoState.ArchiveFile + EngineVersion = '1.1.0' + DocfxVersion = '2.81.0' + Revision = $validRevision + Tags = $validTags + EngineQualifiedTags = $validEngineTags + } + { Test-DocfxPromotionPreflight @base -Tags @() } | Should -Throw '*at least one destination tag*' + { Test-DocfxPromotionPreflight @base -EngineQualifiedTags @() } | Should -Throw '*explicit engine-qualified*' + { Test-DocfxPromotionPreflight @base -Tags @($validTags[0], $validTags[0]) } | Should -Throw '*must be unique*' + { Test-DocfxPromotionPreflight @base -Tags @('codebeltnet/docfx:2-v1.1.0', 'other/docfx:2') } | Should -Throw '*target one repository*' + { Test-DocfxPromotionPreflight @base -EngineQualifiedTags @('codebeltnet/docfx:9-v1.1.0') } | Should -Throw '*must be included in destination tags*' + { Test-DocfxPromotionPreflight @base -Tags @('codebeltnet/docfx:2-v1.0.0') -EngineQualifiedTags @('codebeltnet/docfx:2-v1.0.0') } | Should -Throw '*does not match engine version*' + } + + It 'rejects conflicting engine-qualified tag digest and accepts matching digest for idempotent retry' { + Mock -ModuleName DocfxImage Get-RegistryManifestDigest { + param($Reference) + if ($Reference -ceq 'codebeltnet/docfx:2.81-v1.1.0') { return $global:DocfxPromoState.ConflictDigest } + return $null + } + { + Test-DocfxPromotionPreflight -ArchivePath $global:DocfxPromoState.ArchiveFile -EngineVersion '1.1.0' -DocfxVersion '2.81.0' ` + -Revision $validRevision -Tags $validTags -EngineQualifiedTags $validEngineTags -Platform 'amd64' -ExpectedIndexDigest $global:DocfxPromoState.ComputedDigest + } | Should -Throw '*Engine-qualified tag conflict*Refusing to overwrite*' + + Mock -ModuleName DocfxImage Get-RegistryManifestDigest { return $null } + { + Test-DocfxPromotionPreflight -ArchivePath $global:DocfxPromoState.ArchiveFile -EngineVersion '1.1.0' -DocfxVersion '2.81.0' ` + -Revision $validRevision -Tags $validTags -EngineQualifiedTags $validEngineTags -RequireEngineTagsPresent + } | Should -Throw '*is absent in the registry before convenience tag promotion*' + + Mock -ModuleName DocfxImage Get-RegistryManifestDigest { return $global:DocfxPromoState.ComputedDigest } + $res = Test-DocfxPromotionPreflight -ArchivePath $global:DocfxPromoState.ArchiveFile -EngineVersion '1.1.0' -DocfxVersion '2.81.0' ` + -Revision $validRevision -Tags $validTags -EngineQualifiedTags $validEngineTags -RequireEngineTagsPresent + $res.IndexDigest | Should -Be $global:DocfxPromoState.ComputedDigest + } + + It 'promotes engine-qualified tags first, runs BeforeConvenience, promotes convenience tags, verifies by digest, and writes summary' { + $global:DocfxPromoState.Registry['codebeltnet/docfx:2.81.0-v1.1.0'] = $global:DocfxPromoState.ComputedDigest + + Mock -ModuleName DocfxImage Get-RegistryManifestDigest { + param($Reference) + if ($global:DocfxPromoState.Registry.ContainsKey($Reference)) { return $global:DocfxPromoState.Registry[$Reference] } + return $null + } + Mock -ModuleName DocfxImage Invoke-Skopeo { + param([string[]] $Arguments, [switch] $CaptureOutput) + $s = $global:DocfxPromoState + if ($Arguments[0] -ceq 'inspect') { return $s.RawIndexBytes } + if ($Arguments[3].StartsWith('docker://')) { + $s.Events.Add('verify-download') + return + } + $dest = $Arguments[-1].Substring('docker://'.Length) + $s.Registry[$dest] = $s.ComputedDigest + $s.Events.Add("push:$dest") + } + + $summaryPath = Join-Path $TestDrive 'summary.md' + $prevSummary = $env:GITHUB_STEP_SUMMARY + try { + $env:GITHUB_STEP_SUMMARY = $summaryPath + $result = Publish-DocfxOciArchive ` + -ArchivePath $global:DocfxPromoState.ArchiveFile ` + -EngineVersion '1.1.0' ` + -DocfxVersion '2.81.0' ` + -Revision $validRevision ` + -Tags $validTags ` + -EngineQualifiedTags $validEngineTags ` + -ExpectedIndexDigest $global:DocfxPromoState.ComputedDigest ` + -Platform 'amd64' ` + -BeforeConvenience { $global:DocfxPromoState.Events.Add('before-convenience') } + } finally { + $env:GITHUB_STEP_SUMMARY = $prevSummary + } + + $result.Published.Count | Should -Be 7 + $global:DocfxPromoState.Events | Should -Be @( + 'push:codebeltnet/docfx:2.81-v1.1.0' + 'push:codebeltnet/docfx:2-v1.1.0' + 'before-convenience' + 'push:codebeltnet/docfx:2.81.0' + 'push:codebeltnet/docfx:2.81' + 'push:codebeltnet/docfx:2' + 'push:codebeltnet/docfx:latest' + 'verify-download' + ) + Test-Path -LiteralPath "$($global:DocfxPromoState.ArchiveFile).published.json" | Should -BeTrue + (Get-Content -LiteralPath $summaryPath -Raw) | Should -BeLike "*$($global:DocfxPromoState.ComputedDigest)*" + } + + It 'fails when concurrent conflict occurs on recheck or when registry rewrites index digest' { + Mock -ModuleName DocfxImage Get-RegistryManifestDigest { + $global:DocfxPromoState.CallNum++ + if ($global:DocfxPromoState.CallNum -le 3) { return $null } + return $global:DocfxPromoState.ConflictDigest + } + { + Publish-DocfxOciArchive -ArchivePath $global:DocfxPromoState.ArchiveFile -EngineVersion '1.1.0' -DocfxVersion '2.81.0' ` + -Revision $validRevision -Tags $validTags -EngineQualifiedTags $validEngineTags + } | Should -Throw '*Engine-qualified tag conflict*Refusing to overwrite*' + + Mock -ModuleName DocfxImage Get-RegistryManifestDigest { return $null } + Mock -ModuleName DocfxImage Invoke-Skopeo { + param([string[]] $Arguments, [switch] $CaptureOutput) + if ($Arguments[0] -ceq 'inspect') { return [Text.Encoding]::UTF8.GetBytes('rewritten-bytes') } + } + { + Publish-DocfxOciArchive -ArchivePath $global:DocfxPromoState.ArchiveFile -EngineVersion '1.1.0' -DocfxVersion '2.81.0' ` + -Revision $validRevision -Tags $validTags -EngineQualifiedTags $validEngineTags + } | Should -Throw '*Registry OCI index digest changed*' + + Mock -ModuleName DocfxImage Get-RegistryManifestDigest { return $global:DocfxPromoState.ComputedDigest } + Mock -ModuleName DocfxImage Invoke-Skopeo { + param([string[]] $Arguments, [switch] $CaptureOutput) + if ($Arguments[0] -ceq 'inspect') { + $global:DocfxPromoState.InspectCount++ + if ($global:DocfxPromoState.InspectCount -le 3) { return $global:DocfxPromoState.RawIndexBytes } + return [Text.Encoding]::UTF8.GetBytes('rewritten-convenience') + } + } + { + Publish-DocfxOciArchive -ArchivePath $global:DocfxPromoState.ArchiveFile -EngineVersion '1.1.0' -DocfxVersion '2.81.0' ` + -Revision $validRevision -Tags $validTags -EngineQualifiedTags $validEngineTags + } | Should -Throw '*Registry OCI index digest changed*' + } + } +} + +Describe 'Invoke-DocfxRelease CI/CD lifecycle orchestration' { + BeforeEach { + $script:savedEnv = @{ + GITHUB_REF_NAME = $env:GITHUB_REF_NAME + GITHUB_SHA = $env:GITHUB_SHA + GITHUB_REPOSITORY = $env:GITHUB_REPOSITORY + GITHUB_EVENT_NAME = $env:GITHUB_EVENT_NAME + GITHUB_EVENT_PATH = $env:GITHUB_EVENT_PATH + GITHUB_REF = $env:GITHUB_REF + GITHUB_RUN_ID = $env:GITHUB_RUN_ID + GITHUB_RUN_ATTEMPT = $env:GITHUB_RUN_ATTEMPT + GITHUB_OUTPUT = $env:GITHUB_OUTPUT + GITHUB_STEP_SUMMARY = $env:GITHUB_STEP_SUMMARY + RELEASE_TAG = $env:RELEASE_TAG + } + $script:work = Join-Path $TestDrive ('rel-' + [guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $script:work -Force | Out-Null + $env:GITHUB_REPOSITORY = 'codebeltnet/docfx' + $env:GITHUB_REF_NAME = 'v1.1.0' + $env:RELEASE_TAG = 'v1.1.0' + $env:GITHUB_SHA = $validRevision + $env:GITHUB_RUN_ID = '9001' + $env:GITHUB_RUN_ATTEMPT = '1' + $env:GITHUB_OUTPUT = Join-Path $script:work 'github-output.txt' + $env:GITHUB_STEP_SUMMARY = Join-Path $script:work 'github-summary.md' + + $global:DocfxRelTestState = @{ + GhMap = @{} + } + } + + AfterEach { + foreach ($key in $script:savedEnv.Keys) { + if ($null -eq $script:savedEnv[$key]) { Remove-Item "Env:$key" -ErrorAction SilentlyContinue } + else { Set-Item "Env:$key" -Value $script:savedEnv[$key] } + } + Remove-Item Function:global:gh -ErrorAction SilentlyContinue + Remove-Variable DocfxRelTestState -Scope Global -ErrorAction SilentlyContinue + } + + Context 'ValidateTag' { + It 'validates tag, revision, and version consistency and emits GitHub outputs' { + Mock Get-DocfxSourceRevision { return ('a' * 40) } + $out = & $releaseScript -Command ValidateTag + $out | Should -BeLike '*Validated release tag v1.1.0*' + (Get-Content -LiteralPath $env:GITHUB_OUTPUT -Raw) | Should -BeLike '*engine-version=1.1.0*docfx-version=2.81.0*' + + $env:GITHUB_SHA = 'b' * 40 + { & $releaseScript -Command ValidateTag } | Should -Throw '*does not match GITHUB_SHA*' + } + } + + Context 'Assemble, Split, and VerifyDraftAssets' { + BeforeEach { + $script:inputsDir = Join-Path $script:work 'inputs' + $script:outDir = Join-Path $script:work 'out' + $script:assetsDir = Join-Path $script:work 'assets' + foreach ($cpu in 'amd64', 'arm64') { + $dir = Join-Path $script:inputsDir "container-$cpu" + New-Item -ItemType Directory -Path $dir -Force | Out-Null + $archivePath = Join-Path $dir "docfx.$cpu.oci.tar" + Set-Content -LiteralPath $archivePath "archive-$cpu" + $cfg = if ($cpu -ceq 'amd64') { $amd64Config } else { $arm64Config } + @{ + DocfxVersion = '2.81.0' + EngineVersion = '1.1.0' + Repository = 'codebeltnet/docfx' + SourceRepository = 'https://github.com/codebeltnet/docfx' + SourceCommit = $validRevision + Platform = "linux/$cpu" + Architecture = $cpu + Tags = $validTags + ConvenienceTags = $validConvenienceTags + EngineQualifiedTags = $validEngineTags + ConfigDigest = $cfg + SizeBytes = 1000 + ArchiveSha256 = (Get-FileHash -LiteralPath $archivePath).Hash.ToLowerInvariant() + OciArchiveBytes = (Get-Item -LiteralPath $archivePath).Length + NativeVerified = $true + } | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $dir 'docfx-image.json') + } + + Mock Invoke-OciArtifact { + param([string[]] $Arguments) + switch ($Arguments[0]) { + 'verify' { + $cpu = $Arguments[[Array]::IndexOf($Arguments, '--platform') + 1] + $cfg = if ($cpu -ceq 'amd64') { 'sha256:' + ('2' * 64) } else { 'sha256:' + ('3' * 64) } + $hash = (Get-FileHash -LiteralPath $Arguments[1]).Hash.ToLowerInvariant() + (@{ indexDigest = 'sha256:' + ('1' * 64); archiveSha256 = $hash; platforms = @($cpu); configs = @{ $cpu = $cfg } } | ConvertTo-Json -Compress) + } + 'merge' { + Set-Content -LiteralPath $Arguments[1] 'merged-oci-tar' + (@{ indexDigest = 'sha256:' + ('1' * 64); archiveSha256 = ('f' * 64); archiveBytes = 14; platforms = @('amd64', 'arm64') } | ConvertTo-Json -Compress) + } + 'split' { + $outDirArg = $Arguments[[Array]::IndexOf($Arguments, '--output-dir') + 1] + Set-Content -LiteralPath (Join-Path $outDirArg 'docfx.oci.part000') 'part-zero' + Set-Content -LiteralPath (Join-Path $outDirArg 'docfx.oci.tar.sha256') (('f' * 64) + ' docfx.oci.tar') + (@{ archiveSha256 = ('f' * 64); archiveBytes = 14; pieces = @(@{ name = 'docfx.oci.part000'; sha256 = ('d' * 64); size = 9 }) } | ConvertTo-Json -Compress) + } + } + } + } + + It 'assembles both native verified archives, writes release.json, splits assets, and verifies draft assets' { + $out = & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir + $out | Should -BeLike "*Assembled multi-platform OCI index $validIndexDigest*" + Test-Path -LiteralPath (Join-Path $script:outDir 'release.json') | Should -BeTrue + Test-Path -LiteralPath $env:GITHUB_STEP_SUMMARY | Should -BeTrue + + $splitOut = & $releaseScript -Command Split -OutDir $script:outDir -AssetsDir $script:assetsDir + $splitOut | Should -BeLike '*Prepared 1 release asset piece*' + Test-Path -LiteralPath (Join-Path $script:assetsDir 'docfx-release.json') | Should -BeTrue + + { & $releaseScript -Command Split -OutDir (Join-Path $script:work 'empty-out') -AssetsDir $script:assetsDir } | Should -Throw '*Expected assembled archive*' + + $files = Get-ChildItem -LiteralPath $script:assetsDir -File + $remoteAssets = @(foreach ($f in $files) { + @{ + name = $f.Name + size = $f.Length + digest = 'sha256:' + (Get-FileHash -LiteralPath $f.FullName -Algorithm SHA256).Hash.ToLowerInvariant() + } + }) + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/releases?per_page=30'] = @(@{ tag_name = 'v1.1.0'; draft = $true; assets = $remoteAssets }) + function global:gh { + $endpoint = $args[1] + if ($global:DocfxRelTestState.GhMap.ContainsKey($endpoint)) { + $global:LASTEXITCODE = 0 + return (ConvertTo-Json -InputObject $global:DocfxRelTestState.GhMap[$endpoint] -Depth 10) + } + $global:LASTEXITCODE = 1 + return 'not found' + } + + $vOut = & $releaseScript -Command VerifyDraftAssets -ReleaseDir $script:assetsDir + $vOut | Should -BeLike '*Verified 3 durable asset*' + + $emptyRel = Join-Path $script:work 'empty-rel' + New-Item -ItemType Directory -Path $emptyRel -Force | Out-Null + { & $releaseScript -Command VerifyDraftAssets -ReleaseDir $emptyRel } | Should -Throw '*No release asset files*' + + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/releases?per_page=30'] = @() + { & $releaseScript -Command VerifyDraftAssets -ReleaseDir $script:assetsDir } | Should -Throw '*Expected exactly one draft*' + + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/releases?per_page=30'] = @(@{ tag_name = 'v1.1.0'; draft = $true; assets = @($remoteAssets[0]) }) + { & $releaseScript -Command VerifyDraftAssets -ReleaseDir $script:assetsDir } | Should -Throw '*missing expected asset*' + + $badSize = @($remoteAssets | ForEach-Object { $_.Clone() }) + $badSize[0].size = 999999 + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/releases?per_page=30'] = @(@{ tag_name = 'v1.1.0'; draft = $true; assets = $badSize }) + { & $releaseScript -Command VerifyDraftAssets -ReleaseDir $script:assetsDir } | Should -Throw '*size mismatch*' + + $badDigest = @($remoteAssets | ForEach-Object { $_.Clone() }) + $badDigest[0].digest = 'sha256:' + ('0' * 64) + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/releases?per_page=30'] = @(@{ tag_name = 'v1.1.0'; draft = $true; assets = $badDigest }) + { & $releaseScript -Command VerifyDraftAssets -ReleaseDir $script:assetsDir } | Should -Throw '*digest mismatch*' + + $global:DocfxRelTestState.GhMap.Clear() + { & $releaseScript -Command VerifyDraftAssets -ReleaseDir $script:assetsDir } | Should -Throw '*gh api*exited with code 1*' + } + + It 'rejects a native record with a mismatched before merging' -ForEach @( + @{ Field = 'ArchiveSha256'; Value = '0' * 64; Expected = '*arm64*OCI archive SHA-256*' } + @{ Field = 'OciArchiveBytes'; Value = 500; Expected = '*arm64*OCI archive size*' } + ) { + $recordPath = Join-Path $script:inputsDir 'container-arm64/docfx-image.json' + $record = Get-Content -LiteralPath $recordPath -Raw | ConvertFrom-Json -AsHashtable + $record[$Field] = $Value + $record | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $recordPath + + { & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir } | Should -Throw $Expected + Should -Invoke Invoke-OciArtifact -Times 0 -Exactly -ParameterFilter { $Arguments[0] -eq 'merge' } + } + + It 'rejects assembly failures (missing records, unverified, identity/tag/platform/archive/config mismatches)' { + $amdMetaPath = Join-Path $script:inputsDir 'container-amd64/docfx-image.json' + $m = Get-Content -LiteralPath $amdMetaPath -Raw | ConvertFrom-Json -AsHashtable + $m.NativeVerified = $false + $m | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $amdMetaPath + { & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir } | Should -Throw '*is not verified*' + + $m.NativeVerified = $true + $m.EngineVersion = '1.0.9' + $m | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $amdMetaPath + { & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir } | Should -Throw '*identity mismatch*' + + $m.EngineVersion = '1.1.0' + $m.Tags = @('codebeltnet/docfx:other') + $m | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $amdMetaPath + { & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir } | Should -Throw '*tag mismatch*' + + $m.Tags = $validTags + $m.Platform = 'linux/arm64' + $m | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $amdMetaPath + { & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir } | Should -Throw '*Both native CPUs*' + + $m.Platform = 'linux/amd64' + $m | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $amdMetaPath + $env:GITHUB_SHA = 'b' * 40 + { & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir } | Should -Throw '*does not match native verification records*' + $env:GITHUB_SHA = $validRevision + + foreach ($cpu in 'amd64', 'arm64') { + $p = Join-Path $script:inputsDir "container-$cpu/docfx-image.json" + $x = Get-Content -LiteralPath $p -Raw | ConvertFrom-Json -AsHashtable + $x.Tags = @('codebeltnet/docfx:wrong') + $x | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $p + } + { & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir } | Should -Throw '*differs from authoritative BuildAndPushDocfxImage*' + foreach ($cpu in 'amd64', 'arm64') { + $p = Join-Path $script:inputsDir "container-$cpu/docfx-image.json" + $x = Get-Content -LiteralPath $p -Raw | ConvertFrom-Json -AsHashtable + $x.Tags = $validTags + $x | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $p + } + + $m.ConfigDigest = 'sha256:' + ('0' * 64) + $m | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $amdMetaPath + { & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir } | Should -Throw '*does not match the assembled OCI image config digest*' + + Remove-Item -LiteralPath (Join-Path $script:inputsDir 'container-arm64/docfx.arm64.oci.tar') + { & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir } | Should -Throw '*Exactly two native OCI archives*' + + Remove-Item -LiteralPath (Join-Path $script:inputsDir 'container-arm64/docfx-image.json') + { & $releaseScript -Command Assemble -InputsDir $script:inputsDir -OutDir $script:outDir } | Should -Throw '*Both native verification records*' + } + } + + Context 'Resolve, Restore, and Publish (including stale-release protection and recovery)' { + BeforeEach { + $script:resolvedDir = Join-Path $script:work 'resolved' + $script:outDir = Join-Path $script:work 'out' + $script:assetStore = Join-Path $script:work 'remote-assets' + New-Item -ItemType Directory -Path $script:assetStore -Force | Out-Null + + $partContent = 'part-zero-bytes' + $partFile = Join-Path $script:assetStore 'docfx.oci.part000' + Set-Content -LiteralPath $partFile $partContent -NoNewline + $partHash = (Get-FileHash -LiteralPath $partFile -Algorithm SHA256).Hash.ToLowerInvariant() + $partSize = (Get-Item -LiteralPath $partFile).Length + + $checksumFile = Join-Path $script:assetStore 'docfx.oci.tar.sha256' + Set-Content -LiteralPath $checksumFile "$partHash docfx.oci.tar`n" -NoNewline + $checksumHash = (Get-FileHash -LiteralPath $checksumFile -Algorithm SHA256).Hash.ToLowerInvariant() + $checksumSize = (Get-Item -LiteralPath $checksumFile).Length + + $script:releaseMetaObj = @{ + ReleaseTag = 'v1.1.0' + DocfxVersion = '2.81.0' + EngineVersion = '1.1.0' + SourceCommit = $validRevision + SourceRepository = 'https://github.com/codebeltnet/docfx' + Repository = 'codebeltnet/docfx' + Tags = $validTags + ConvenienceTags = $validConvenienceTags + EngineQualifiedTags = $validEngineTags + OciIndexDigest = $validIndexDigest + ArchiveSha256 = $partHash + ArchiveBytes = $partSize + ReleaseRunId = '9001' + ReleaseRunAttempt = '1' + Pieces = @(@{ Name = 'docfx.oci.part000'; Sha256 = $partHash; Size = $partSize }) + Verification = @( + @{ Platform = 'linux/amd64'; Architecture = 'amd64'; NativeVerified = $true; DocfxVersion = '2.81.0'; EngineVersion = '1.1.0'; SourceCommit = $validRevision; Tags = $validTags; ConvenienceTags = $validConvenienceTags; EngineQualifiedTags = $validEngineTags; SizeBytes = 1000; OciArchiveBytes = 500 } + @{ Platform = 'linux/arm64'; Architecture = 'arm64'; NativeVerified = $true; DocfxVersion = '2.81.0'; EngineVersion = '1.1.0'; SourceCommit = $validRevision; Tags = $validTags; ConvenienceTags = $validConvenienceTags; EngineQualifiedTags = $validEngineTags; SizeBytes = 1000; OciArchiveBytes = 500 } + ) + } + $relJsonFile = Join-Path $script:assetStore 'docfx-release.json' + $script:releaseMetaObj | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $relJsonFile -NoNewline + $relJsonHash = (Get-FileHash -LiteralPath $relJsonFile -Algorithm SHA256).Hash.ToLowerInvariant() + $relJsonSize = (Get-Item -LiteralPath $relJsonFile).Length + + $script:releaseAssets = @( + @{ name = 'docfx-release.json'; size = $relJsonSize; digest = "sha256:$relJsonHash"; browser_download_url = $relJsonFile } + @{ name = 'docfx.oci.tar.sha256'; size = $checksumSize; digest = "sha256:$checksumHash"; browser_download_url = $checksumFile } + @{ name = 'docfx.oci.part000'; size = $partSize; digest = "sha256:$partHash"; browser_download_url = $partFile } + ) + + $global:DocfxRelTestState.GhMap = @{ + 'repos/codebeltnet/docfx/releases/tags/v1.1.0' = @{ id = 42; tag_name = 'v1.1.0'; draft = $false; prerelease = $false; published_at = '2026-11-25T12:00:00Z'; assets = $script:releaseAssets } + 'repos/codebeltnet/docfx/releases/latest' = @{ id = 42; tag_name = 'v1.1.0'; draft = $false; prerelease = $false; published_at = '2026-11-25T12:00:00Z' } + 'repos/codebeltnet/docfx/commits/v1.1.0' = @{ sha = $validRevision } + "repos/codebeltnet/docfx/compare/$validRevision...main" = @{ status = 'identical' } + 'repos/codebeltnet/docfx/actions/runs/9001/attempts/1' = @{ event = 'push'; path = '.github/workflows/release.yml'; head_sha = $validRevision; head_branch = 'v1.1.0'; run_attempt = 1; conclusion = 'success' } + } + + function global:gh { + $endpoint = $args[1] + if ($global:DocfxRelTestState.GhMap.ContainsKey($endpoint)) { + $global:LASTEXITCODE = 0 + return (ConvertTo-Json -InputObject $global:DocfxRelTestState.GhMap[$endpoint] -Depth 12) + } + $global:LASTEXITCODE = 1 + return "unexpected endpoint: $endpoint" + } + + Mock Invoke-WebRequest { + param($Uri, $OutFile) + $sourcePath = if ($Uri -is [uri] -and $Uri.IsFile) { $Uri.LocalPath } else { [string]$Uri } + Copy-Item -LiteralPath $sourcePath -Destination $OutFile -Force + } + } + + It 'resolves published release event and workflow_dispatch from main, and rejects drafts, older releases, non-main branches, and bad ancestry' { + $env:GITHUB_EVENT_NAME = 'workflow_dispatch' + $env:GITHUB_REF = 'refs/heads/main' + $resOut = & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir + $resOut | Should -BeLike '*Resolved latest published release v1.1.0*' + + $eventFile = Join-Path $script:work 'event.json' + @{ action = 'published'; release = @{ id = 42; tag_name = 'v1.1.0' } } | ConvertTo-Json | Set-Content -LiteralPath $eventFile + $env:GITHUB_EVENT_NAME = 'release' + $env:GITHUB_EVENT_PATH = $eventFile + & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir | Should -BeLike '*Resolved latest published release*' + + @{ action = 'published'; release = @{ id = 999; tag_name = 'v1.1.0' } } | ConvertTo-Json | Set-Content -LiteralPath $eventFile + { & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir } | Should -Throw '*Published release ID changed*' + + @{ action = 'created'; release = @{ id = 42; tag_name = 'v1.1.0' } } | ConvertTo-Json | Set-Content -LiteralPath $eventFile + { & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir } | Should -Throw '*Unexpected release event payload*' + + $env:GITHUB_EVENT_NAME = 'workflow_dispatch' + $env:GITHUB_REPOSITORY = 'fork/docfx' + { & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir } | Should -Throw '*restricted to*codebeltnet/docfx*' + $env:GITHUB_REPOSITORY = 'codebeltnet/docfx' + + $env:GITHUB_REF = 'refs/heads/feature' + { & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir } | Should -Throw '*dispatched from*refs/heads/main*' + $env:GITHUB_REF = 'refs/heads/main' + + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/releases/latest'] = @{ id = 99; tag_name = 'v1.2.0'; draft = $false; prerelease = $false } + { & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir } | Should -Throw '*latest published stable release*' + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/releases/latest'] = @{ id = 42; tag_name = 'v1.1.0'; draft = $false; prerelease = $false } + + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/commits/v1.1.0'] = @{ sha = 'invalid' } + { & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir } | Should -Throw '*Unable to resolve commit SHA*' + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/commits/v1.1.0'] = @{ sha = $validRevision } + + $global:DocfxRelTestState.GhMap["repos/codebeltnet/docfx/compare/$validRevision...main"] = @{ status = 'diverged' } + { & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir } | Should -Throw '*not in main branch history*' + $global:DocfxRelTestState.GhMap["repos/codebeltnet/docfx/compare/$validRevision...main"] = @{ status = 'identical' } + + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/releases/tags/v1.1.0'].assets = @() + { & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir } | Should -Throw '*missing required durable asset*' + } + + It 'restores and verifies release assets and rejects invalid runs, identities, pieces, or asset checksums' { + $env:GITHUB_EVENT_NAME = 'workflow_dispatch' + $env:GITHUB_REF = 'refs/heads/main' + $null = & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir + + Mock Invoke-OciArtifact { + param([string[]] $Arguments) + if ($Arguments[0] -ceq 'reassemble') { + $outPath = $Arguments[[Array]::IndexOf($Arguments, '--output') + 1] + Set-Content -LiteralPath $outPath 'rebuilt-archive' + return '{"archiveSha256":"' + ('a' * 64) + '","archiveBytes":15}' + } + return (@{ indexDigest = 'sha256:' + ('1' * 64); platforms = @('amd64', 'arm64') } | ConvertTo-Json -Compress) + } + + { & $releaseScript -Command Restore -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Not -Throw + + { & $releaseScript -Command Restore -ResolvedDir (Join-Path $script:work 'no-resolved') -OutDir $script:outDir } | Should -Throw '*identity file is missing*' + + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/actions/runs/9001/attempts/1'].conclusion = 'failure' + { & $releaseScript -Command Restore -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Throw '*Authoritative tag release workflow run did not succeed*' + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/actions/runs/9001/attempts/1'].conclusion = 'success' + + $idPath = Join-Path $script:resolvedDir 'identity.json' + $idObj = Get-Content -LiteralPath $idPath -Raw | ConvertFrom-Json -AsHashtable + $origDigest = $idObj.assets['docfx-release.json'].digest + $idObj.assets['docfx-release.json'].digest = '' + $idObj | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $idPath + { & $releaseScript -Command Restore -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Throw '*no authoritative SHA-256 digest*' + + $idObj.assets['docfx-release.json'].digest = $origDigest + $origUrl = $idObj.assets['docfx-release.json'].browser_download_url + $idObj.assets['docfx-release.json'].browser_download_url = '' + $idObj | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $idPath + { & $releaseScript -Command Restore -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Throw '*no download URL*' + + $idObj.assets['docfx-release.json'].browser_download_url = $origUrl + $idObj.assets['docfx-release.json'].digest = 'sha256:' + ('0' * 64) + $idObj | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $idPath + { & $releaseScript -Command Restore -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Throw '*checksum or size mismatch*' + $idObj.assets['docfx-release.json'].digest = $origDigest + $idObj | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $idPath + + function Update-ReleaseMeta([scriptblock] $Mutate) { + $copy = $script:releaseMetaObj | ConvertTo-Json -Depth 10 | ConvertFrom-Json -AsHashtable + & $Mutate $copy + $relFile = Join-Path $script:assetStore 'docfx-release.json' + $copy | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $relFile -NoNewline + $idObj.assets['docfx-release.json'].digest = 'sha256:' + (Get-FileHash -LiteralPath $relFile -Algorithm SHA256).Hash.ToLowerInvariant() + $idObj.assets['docfx-release.json'].size = (Get-Item -LiteralPath $relFile).Length + $idObj | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $idPath + } + + Update-ReleaseMeta { param($c) $c.EngineVersion = '1.0.9' } + { & $releaseScript -Command Restore -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Throw '*does not match the resolved published release identity*' + + Update-ReleaseMeta { param($c) $c.Verification = @($c.Verification[0]) } + { & $releaseScript -Command Restore -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Throw '*Both native architecture verification records*' + + Update-ReleaseMeta { param($c) $c.Verification[0].NativeVerified = $false } + { & $releaseScript -Command Restore -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Throw '*Native verification record identity mismatch*' + + Update-ReleaseMeta { param($c) $c.Pieces = @(@{ Name = '../escape.tar'; Sha256 = ('a' * 64); Size = 10 }) } + { & $releaseScript -Command Restore -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Throw '*Invalid release archive piece name*' + + Update-ReleaseMeta { param($c) $c.Pieces = @(@{ Name = 'docfx.oci.part999'; Sha256 = ('a' * 64); Size = 10 }) } + { & $releaseScript -Command Restore -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Throw '*missing archive piece*' + } + + It 'publishes via Publish-DocfxOciArchive and blocks promotion if latest release changes' { + $env:GITHUB_EVENT_NAME = 'workflow_dispatch' + $env:GITHUB_REF = 'refs/heads/main' + $null = & $releaseScript -Command Resolve -ResolvedDir $script:resolvedDir + + Mock Invoke-OciArtifact { + param([string[]] $Arguments) + if ($Arguments[0] -ceq 'reassemble') { + $outPath = $Arguments[[Array]::IndexOf($Arguments, '--output') + 1] + Set-Content -LiteralPath $outPath 'rebuilt-archive' + return '{"archiveSha256":"' + ('a' * 64) + '","archiveBytes":15}' + } + return (@{ indexDigest = 'sha256:' + ('1' * 64); platforms = @('amd64', 'arm64') } | ConvertTo-Json -Compress) + } + Mock Publish-DocfxOciArchive { + param([scriptblock] $BeforeConvenience) + if ($BeforeConvenience) { & $BeforeConvenience } + [pscustomobject]@{ + IndexDigest = 'sha256:' + ('1' * 64) + Repository = 'codebeltnet/docfx' + Published = @('1','2','3','4','5','6','7' | ForEach-Object { @{ tag = "t$_"; digest = 'sha256:' + ('1' * 64) } }) + } + } + + $pubOut = & $releaseScript -Command Publish -ResolvedDir $script:resolvedDir -OutDir $script:outDir + $pubOut | Should -BeLike "*Promoted 7 tags to codebeltnet/docfx@$validIndexDigest*" + + { & $releaseScript -Command Publish -ResolvedDir (Join-Path $script:work 'no-resolved') -OutDir $script:outDir } | Should -Throw '*identity file is missing*' + + $global:DocfxRelTestState.GhMap['repos/codebeltnet/docfx/releases/latest'] = @{ id = 99; tag_name = 'v1.2.0'; draft = $false; prerelease = $false } + { & $releaseScript -Command Publish -ResolvedDir $script:resolvedDir -OutDir $script:outDir } | Should -Throw '*Latest published release changed*refusing stale*' + } + } +} diff --git a/tests/Test-DocfxContainer.ps1 b/tests/Test-DocfxContainer.ps1 new file mode 100644 index 0000000..668c5c4 --- /dev/null +++ b/tests/Test-DocfxContainer.ps1 @@ -0,0 +1,224 @@ +#requires -Version 7.0 +[CmdletBinding()] +param( + [Parameter(Mandatory)][string] $Image, + [ValidateSet('linux/amd64', 'linux/arm64')][string] $Platform = 'linux/amd64', + [string] $DocfxVersion, + [string] $EngineVersion, + [string] $Revision, + [string] $SourceRepository = 'https://github.com/codebeltnet/docfx', + [switch] $RequireNative +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $false + +$repoRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path +Import-Module (Join-Path $repoRoot 'tools/DocfxImage.psm1') -Force + +if (-not $DocfxVersion) { + $DocfxVersion = Get-DocfxDefaultVersion -RootPath $repoRoot +} + +$expectedArch = ($Platform -split '/')[1] +$expectedRuntimeArch = if ($expectedArch -ceq 'amd64') { 'X64' } else { 'Arm64' } +$expectedCompat = "framework-views-v1/docfx-$DocfxVersion" + +if ($RequireNative) { + Assert-NativeDockerHost -Platform $Platform +} + +function Invoke-ContainerCommand { + param([Parameter(Mandatory)][string[]] $Arguments) + + $output = & docker @Arguments 2>&1 + if ($LASTEXITCODE -ne 0) { + $text = (@($output) | ForEach-Object { $_.ToString() }) -join "`n" + throw "docker $($Arguments -join ' ') failed with exit code $LASTEXITCODE`:`n$text" + } + @($output | ForEach-Object { $_.ToString() }) +} + +Write-Host "Validating DocFX builder image '$Image' on $Platform (DocFX $DocfxVersion, engine '$EngineVersion')..." + +# 1. OCI image metadata and architecture +$inspect = (Invoke-ContainerCommand @('image', 'inspect', $Image)) -join "`n" | ConvertFrom-Json +$info = @($inspect)[0] +if ($info.Os -cne 'linux' -or $info.Architecture -cne $expectedArch) { + throw "Image OS/architecture mismatch: expected linux/$expectedArch, found $($info.Os)/$($info.Architecture)." +} + +$labels = $info.Config.Labels +if ($labels.'net.codebelt.docfx.cli.version' -cne $DocfxVersion) { + throw "Image label net.codebelt.docfx.cli.version expected '$DocfxVersion', found '$($labels.'net.codebelt.docfx.cli.version')'." +} +if ($labels.'org.opencontainers.image.source' -cne $SourceRepository) { + throw "Image label org.opencontainers.image.source expected '$SourceRepository', found '$($labels.'org.opencontainers.image.source')'." +} +if ($EngineVersion) { + if ($labels.'org.opencontainers.image.version' -cne $EngineVersion -or + $labels.'net.codebelt.docfx.engine.version' -cne $EngineVersion) { + throw "Image engine version labels do not match expected '$EngineVersion'." + } +} +if ($Revision) { + if ($labels.'org.opencontainers.image.revision' -cne $Revision) { + throw "Image label org.opencontainers.image.revision expected '$Revision', found '$($labels.'org.opencontainers.image.revision')'." + } +} +if ([string]::IsNullOrWhiteSpace($labels.'org.opencontainers.image.created')) { + throw 'Image label org.opencontainers.image.created is missing.' +} + +# 2. PowerShell 7, native runtime CPU architecture, DocFX CLI version, and included .NET SDKs +$pwshInfo = (Invoke-ContainerCommand @('run', '--rm', '--platform', $Platform, $Image, 'pwsh', '-NoProfile', '-Command', '$PSVersionTable.PSVersion.ToString() + "|" + [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture')) -join '' +$pwshVersion, $runtimeArch = $pwshInfo.Trim().Split('|', 2) +if ($pwshVersion -notmatch '^7\.' -or $runtimeArch -cne $expectedRuntimeArch) { + throw "Unexpected PowerShell or process architecture: '$pwshInfo' (expected PowerShell 7 on $expectedRuntimeArch)." +} + +$docfxActual = ((Invoke-ContainerCommand @('run', '--rm', '--platform', $Platform, $Image, 'docfx', '--version')) -join '').Trim() +if (($docfxActual -split '\+', 2)[0] -cne $DocfxVersion) { + throw "Unexpected DocFX CLI version '$docfxActual'; expected '$DocfxVersion'." +} + +$sdkLines = Invoke-ContainerCommand @('run', '--rm', '--platform', $Platform, $Image, 'dotnet', '--list-sdks') +$sdkMajors = @($sdkLines | ForEach-Object { if ($_ -match '^(\d+)\.') { $Matches[1] } } | Select-Object -Unique) +if ('10' -cnotin $sdkMajors -or '11' -cnotin $sdkMajors) { + throw "Expected both .NET 10 and .NET 11 SDKs in the builder image; found: $($sdkLines -join '; ')." +} + +# 3. Template compatibility and complete framework-views generator distribution +$distributionCheck = @' +$ErrorActionPreference = 'Stop' +$requiredFiles = @( + '/opt/docfx/templates/default', + '/opt/docfx/templates/modern', + '/opt/docfx/templates/ms-style/framework-views.compat', + '/opt/docfx/templates/ms-style/public/framework-view.js', + '/build/docfx/templates/ms-style/framework-views.compat', + '/opt/docfx/framework-views/Build-DocfxFrameworkViews.ps1', + '/opt/docfx/framework-views/FrameworkViewConventions.ps1', + '/opt/docfx/framework-views/DocfxMetadata.ps1', + '/opt/docfx/framework-views/Resolve-DocfxProjects.cs', + '/opt/docfx/framework-views/KeepCrossTargetReferences.targets', + '/opt/docfx/framework-views/framework-views.nginx.conf', + '/opt/docfx/framework-views/framework-views.Dockerfile' +) +foreach ($item in $requiredFiles) { + if (!(Test-Path -LiteralPath $item)) { throw "Missing packaged asset: $item" } +} +(Get-Content -LiteralPath '/opt/docfx/templates/ms-style/framework-views.compat' -Raw).Trim() +'@ +$actualCompat = ((Invoke-ContainerCommand @('run', '--rm', '--platform', $Platform, $Image, 'pwsh', '-NoProfile', '-Command', $distributionCheck)) -join '').Trim() +if ($actualCompat -cne $expectedCompat) { + throw "Packaged ms-style compatibility marker expected '$expectedCompat', found '$actualCompat'." +} + +# 4. Representative multi-framework build, discovery, metadata, manifest, NGINX config, and single-framework build +$work = Join-Path ([IO.Path]::GetTempPath()) ('docfx-container-test-' + [guid]::NewGuid().ToString('N')) +$mount = "type=bind,source=$work,target=/workspace" +New-Item -ItemType Directory -Path $work -Force | Out-Null +try { + $fixture = Join-Path $work 'fixture' + Copy-Item -LiteralPath (Join-Path $repoRoot 'tests/framework-view/fixture') -Destination $fixture -Recurse + $docs = New-Item -ItemType Directory -Path (Join-Path $fixture '.docfx') + Move-Item -LiteralPath (Join-Path $fixture 'docfx.json'), (Join-Path $fixture 'index.md'), (Join-Path $fixture 'toc.yml') -Destination $docs.FullName + + New-Item -ItemType Directory -Path (Join-Path $work 'sdk10') | Out-Null + '{"sdk":{"version":"10.0.100","rollForward":"latestFeature"}}' | Set-Content -LiteralPath (Join-Path $work 'sdk10/global.json') + '{"sdk":{"version":"11.0.100","rollForward":"latestFeature"}}' | Set-Content -LiteralPath (Join-Path $fixture 'global.json') + + $sdk10 = Invoke-ContainerCommand @('run', '--rm', '--platform', $Platform, '--mount', $mount, '-w', '/workspace/sdk10', $Image, 'sh', '-ec', 'dotnet --version && dotnet msbuild -nologo -version') + $sdk11 = (Invoke-ContainerCommand @('run', '--rm', '--platform', $Platform, '--mount', $mount, '-w', '/workspace/fixture', $Image, 'dotnet', '--version')) -join '' + if ($sdk10[0] -notmatch '^10\.' -or $sdk11.Trim() -notmatch '^11\.') { + throw "global.json SDK selection failed inside builder image: SDK10=$($sdk10[0]), SDK11=$sdk11." + } + + $null = Invoke-ContainerCommand @('run', '--rm', '--platform', $Platform, '--mount', $mount, '-w', '/workspace/fixture', $Image, 'pwsh', '-NoProfile', '-File', '/opt/docfx/framework-views/Build-DocfxFrameworkViews.ps1') + + $destination = Join-Path $fixture '.bot/docfx' + if (Get-ChildItem -LiteralPath $destination -Filter 'build-*.log' -Recurse) { + throw 'Ordinary multi-framework metadata generation unexpectedly triggered a recovery build.' + } + foreach ($project in 'Runtime', 'Utilities') { + if (!(Test-Path -LiteralPath (Join-Path $fixture "$project/obj/project.assets.json") -PathType Leaf)) { + throw "Packaged generator did not restore '$project'." + } + } + + $site = Join-Path $destination 'site' + $manifest = Get-Content -LiteralPath (Join-Path $site 'framework-views.json') -Raw | ConvertFrom-Json -AsHashtable + $expectedViews = [ordered]@{ + 'net-11.0' = 'net11' + 'net-10.0' = 'net10' + 'netstandard-2.1' = 'netstandard2.1' + 'netstandard-2.0' = 'netstandard2.0' + 'net48' = 'net48' + } + if ($manifest.schemaVersion -ne 1 -or + $manifest.defaultView -cne 'net-11.0' -or + $manifest.apiPath -cne '/api/' -or + ($manifest.viewOrder -join ',') -cne ($expectedViews.Keys -join ',')) { + throw 'Generated framework-views.json runtime manifest does not match expected views and precedence.' + } + + $nginx = Get-Content -LiteralPath (Join-Path $destination 'nginx.conf') -Raw + if (-not $nginx.Contains('location ^~ /api/') -or $nginx -match '__(API|VIEWS|SEARCH)__') { + throw 'Generated NGINX configuration is incomplete or contains unsubstituted placeholders.' + } + + $widget = 'api/runtime/FrameworkFixture.Runtime.Widget.html' + $availability = @{ + $widget = @($expectedViews.Keys) + 'api/utilities/FrameworkFixture.Utilities.Utility.html' = @($expectedViews.Keys) + 'api/runtime/FrameworkFixture.Runtime.ModernFeature.html' = @('net-11.0', 'net-10.0') + 'api/runtime/FrameworkFixture.Runtime.LegacyFeature.html' = @('net48') + } + foreach ($view in $expectedViews.Keys) { + $directory = $expectedViews[$view] + $viewRoot = if ($view -ceq $manifest.defaultView) { $site } else { Join-Path $site "_frameworks/$directory" } + $index = Get-Content -LiteralPath (Join-Path $viewRoot 'index.json') -Raw | ConvertFrom-Json -AsHashtable + $xrefs = Get-Content -LiteralPath (Join-Path $viewRoot 'xrefmap.yml') -Raw + foreach ($page in $availability.Keys) { + $published = $view -cin $availability[$page] + if ((Test-Path -LiteralPath (Join-Path $viewRoot $page) -PathType Leaf) -ne $published -or + $index.Contains($page) -ne $published -or + $xrefs.Contains("href: $page") -ne $published) { + throw "Unexpected page, search index, or xref availability for '$page' in '$view'." + } + } + if ($manifest.views[$view].directory -cne $directory -or + -not $nginx.Contains("~^$([regex]::Escape($view))$ ") -or + -not $nginx.Contains("~^$([regex]::Escape($directory))$ ")) { + throw "Missing NGINX API or search route for '$view'." + } + } + + if ((Get-Content -LiteralPath (Join-Path $site $widget) -Raw) -notmatch 'id="framework-view"') { + throw 'Packaged ms-style template did not render the framework selector.' + } + + # Verify ordinary single-framework docfx build using packaged templates + $single = Join-Path $work 'single' + New-Item -ItemType Directory -Path $single -Force | Out-Null + Copy-Item -LiteralPath (Join-Path $destination 'net10/api'), (Join-Path $docs 'index.md'), (Join-Path $docs 'toc.yml') -Destination $single -Recurse + $buildCfg = (Get-Content -LiteralPath (Join-Path $docs 'docfx.json') -Raw | ConvertFrom-Json -AsHashtable).build + $buildCfg.template[2] = '/opt/docfx/templates/ms-style' + @{ build = $buildCfg } | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath (Join-Path $single 'docfx.json') + $null = Invoke-ContainerCommand @('run', '--rm', '--platform', $Platform, '--mount', $mount, '-w', '/workspace/single', $Image, 'docfx', 'build', 'docfx.json') + if (!(Test-Path -LiteralPath (Join-Path $single '_site/index.html') -PathType Leaf)) { + throw 'Ordinary single-framework docfx build did not produce _site/index.html.' + } +} finally { + if (Test-Path -LiteralPath $work) { + if ($IsLinux) { + # The packaged CLI runs as root. Return ownership of its bind-mounted outputs to the runner. + $owner = "$(& id -u):$(& id -g)" + $null = Invoke-ContainerCommand @('run', '--rm', '--platform', $Platform, '--mount', $mount, $Image, 'chown', '-Rh', $owner, '/workspace') + } + Remove-Item -LiteralPath $work -Recurse -Force + } +} +Write-Host "PASS: Native container validation passed on $Platform ($runtimeArch): PowerShell $pwshVersion, DocFX $docfxActual, .NET $($sdk10[0]) & $($sdk11.Trim()), 5 framework views + single-framework build." diff --git a/tests/framework-view/Build-DocfxFrameworkViews.Tests.ps1 b/tests/framework-view/Build-DocfxFrameworkViews.Tests.ps1 new file mode 100644 index 0000000..2cf9b11 --- /dev/null +++ b/tests/framework-view/Build-DocfxFrameworkViews.Tests.ps1 @@ -0,0 +1,239 @@ +BeforeAll { + $build = "$PSScriptRoot/../../framework-views/Build-DocfxFrameworkViews.ps1" +} + +Describe 'Framework view build preflight' { + BeforeEach { + $docs = (New-Item -ItemType Directory -Path "$TestDrive/docs" -Force).FullName + $output = "$TestDrive/output" + $config = "$docs/docfx.json" + '{"metadata":[{"dest":"api"}],"build":{}}' | Set-Content -LiteralPath $config + } + + It 'rejects output that overlaps the authored inputs' { + { & $build -DocfxConfig $config -OutputRoot "$docs/generated" } | Should -Throw '*dedicated directory outside the DocFX input directory*' + { & $build -DocfxConfig $config -OutputRoot $TestDrive } | Should -Throw '*dedicated directory outside the DocFX input directory*' + } + + It 'requires an explicit input fingerprint when using a metadata cache' { + { & $build -DocfxConfig $config -OutputRoot $output -MetadataCache "$TestDrive/cache" } | + Should -Throw '*metadata cache requires a metadata input fingerprint*' + } + + It 'rejects a cache that overlaps either the authored inputs or the output' { + foreach ($cache in "$docs/cache", "$output/cache", $TestDrive) { + { & $build -DocfxConfig $config -OutputRoot $output -MetadataCache $cache -MetadataCacheKey 'fixture' } | + Should -Throw '*dedicated metadata cache directory*' + } + } + + It 'rejects an unsafe rendering destination before creating output or cache directories' { + '{"metadata":[{"dest":"api"}],"build":{"dest":"../escape"}}' | Set-Content -LiteralPath $config + $cache = "$TestDrive/cache" + { & $build -DocfxConfig $config -OutputRoot $output -MetadataCache $cache -MetadataCacheKey 'fixture' } | + Should -Throw '*relative DocFX site destination*' + Test-Path -LiteralPath $output | Should -BeFalse + Test-Path -LiteralPath $cache | Should -BeFalse + } +} + +Describe 'Framework view build with stubbed tools' { + BeforeAll { + function dotnet { + $global:LASTEXITCODE = 0 + Add-Content -LiteralPath "$fixture/dotnet.log" -Value ($args -join ' ') + switch ($args[0]) { + '--version' { + if ($scenario -eq 'project SDK failure' -and (Get-Location).Path -eq $docs) { $global:LASTEXITCODE = 1 } + '11.0.100' + } + 'run' { + if ($scenario -eq 'resolver failure') { + $global:LASTEXITCODE = 1 + 'fixture resolver failure' + } else { + $mapping = @{ files = @("$fixture/Library.csproj") } + if ($scenario -ne 'single framework') { $mapping.source = $fixture } + switch ($scenario) { + 'assembly input' { $mapping.files = @("$fixture/Library.dll") } + 'project inside output' { $mapping.files = @("$output/Library.csproj") } + 'empty mapping' { $mapping.files = @() } + } + $mappings = @(, @($mapping)) + if ($scenario -eq 'conflicting properties') { $mappings += , @($mapping) } + ConvertTo-Json -InputObject $mappings -Depth 4 | Set-Content -LiteralPath $args[-1] + } + } + 'msbuild' { + if ($args -contains '-t:PrepareProjectReferences') { + (@{ + Properties = @{ ProduceReferenceAssembly = 'true' } + Items = @{ _MSBuildProjectReferenceExistent = @() } + } | ConvertTo-Json -Depth 4) -split '\r?\n' + } else { + $properties = @{ TargetFrameworks = 'net10.0;net11.0'; TargetFramework = '' } + switch ($scenario) { + 'MSBuild evaluation failure' { $global:LASTEXITCODE = 1 } + 'no frameworks' { $properties.TargetFrameworks = '' } + 'single framework' { $properties.TargetFramework = 'net11.0' } + } + (@{ Properties = $properties } | ConvertTo-Json) -split '\r?\n' + } + } + } + } + } + + BeforeEach { + $previousExitCode = $global:LASTEXITCODE + $fixture = (New-Item -ItemType Directory -Path "$TestDrive/$([guid]::NewGuid())").FullName + $docs = (New-Item -ItemType Directory -Path "$fixture/docs").FullName + $config = "$docs/docfx.json" + $output = "$fixture/output" + $cache = "$fixture/cache" + $cli = "$fixture/docfx.ps1" + $store = (New-Item -ItemType Directory -Path "$fixture/.store/docfx/2.81.0/docfx/2.81.0/tools/net10.0/any").FullName + New-Item -ItemType File -Path "$store/Docfx.Glob.dll", "$fixture/Library.csproj" | Out-Null + $settings = @{ metadata = @(@{ dest = 'api' }); build = @{ template = @('default', 'modern', 'templates/ms-style') } } + ConvertTo-Json $settings -Depth 5 | Set-Content -LiteralPath $config + @' +$global:LASTEXITCODE = 0 +Add-Content -LiteralPath "$PSScriptRoot/docfx.log" -Value ($args -join ' ') +switch ($args[0]) { + '--version' { + switch ($scenario) { + 'CLI version failure' { $global:LASTEXITCODE = 1 } + 'wrong CLI version' { '2.80.0' } + default { '2.81.0' } + } + } + 'metadata' { + $stage = Split-Path -Parent $args[1] + New-Item -ItemType Directory -Path "$stage/api" | Out-Null + '{"Fixture.Library":"Library.yml"}' | Set-Content -LiteralPath "$stage/api/.manifest" + '### YamlMime:ManagedReference' | Set-Content -LiteralPath "$stage/api/Library.yml" + if (Test-Path -LiteralPath "$PSScriptRoot/unresolved") { + "warning: [Warning] Found project reference without a matching metadata reference: $PSScriptRoot/unresolved.csproj" + } else { + 'warning: missing XML comments' + } + } + 'build' { + $stage = Split-Path -Parent $args[1] + $site = Join-Path $stage ((Get-Content -LiteralPath $args[1] -Raw | ConvertFrom-Json).build.dest) + New-Item -ItemType Directory -Path "$site/api" | Out-Null + New-Item -ItemType Directory -Path "$site/public" | Out-Null + 'Fixture.Library' | Set-Content -LiteralPath "$site/api/Library.html" + 'references: []' | Set-Content -LiteralPath "$site/xrefmap.yml" + '{}' | Set-Content -LiteralPath "$site/index.json" + $asset = if ($scenario -eq 'different shared assets') { Split-Path -Leaf $stage } else { 'shared' } + $asset | Set-Content -LiteralPath "$site/public/shared.js" + } +} +'@ | Set-Content -LiteralPath $cli + Mock Get-Command { + if ($scenario -ne 'missing CLI') { [pscustomobject]@{ Source = $cli } } + } -ParameterFilter { $Name -eq 'docfx' } + } + + AfterEach { + $global:LASTEXITCODE = $previousExitCode + } + + It 'continues through rendering on ordinary warnings and skips metadata on a warm cache' { + & $build -DocfxConfig $config -OutputRoot $output -MetadataCache $cache -MetadataCacheKey 'fixture' + Test-Path -LiteralPath "$output/site/api/Library.html" | Should -BeTrue + (Get-Content -LiteralPath "$output/site/framework-views.json" -Raw | ConvertFrom-Json).defaultView | Should -BeExactly 'net-11.0' + @(Get-ChildItem -LiteralPath $cache -Filter '*.zip' -Recurse).Count | Should -Be 2 + & $build -DocfxConfig $config -OutputRoot $output -MetadataCache $cache -MetadataCacheKey 'fixture' + @(Select-String -LiteralPath "$fixture/docfx.log" -Pattern '^metadata .* --noRestore$').Count | Should -Be 2 + @(Select-String -LiteralPath "$fixture/docfx.log" -Pattern '^build ').Count | Should -Be 4 + @(Select-String -LiteralPath "$fixture/dotnet.log" -Pattern '^restore ').Count | Should -Be 1 + Get-Content -LiteralPath "$fixture/dotnet.log" -Raw | Should -Not -Match '(?m)^build |PrepareProjectReferences' + + Set-Content -LiteralPath (Get-ChildItem -LiteralPath $cache -Filter 'net11.0.zip' -Recurse).FullName 'invalid archive' + & $build -DocfxConfig $config -OutputRoot $output -MetadataCache $cache -MetadataCacheKey 'fixture' + Test-Path -LiteralPath "$output/net11/metadata.log" | Should -BeTrue + Test-Path -LiteralPath "$output/net10/metadata.log" | Should -BeFalse + } + + It 'stops before rendering or writing a cache when recovery is unavailable' { + New-Item -ItemType File -Path "$fixture/unresolved" | Out-Null + { & $build -DocfxConfig $config -OutputRoot $output -MetadataCache $cache -MetadataCacheKey 'fixture' } | + Should -Throw '*unresolved project references and recovery was unavailable*metadata.log*' + Test-Path -LiteralPath "$output/site" | Should -BeFalse + @(Get-ChildItem -LiteralPath $cache -Filter '*.zip' -Recurse).Count | Should -Be 0 + Get-Content -LiteralPath "$fixture/docfx.log" -Raw | Should -Not -Match '(?m)^build ' + } + + It 'supports one evaluated framework, the build output alias and NoRestore' { + Set-StrictMode -Version Latest + $scenario = 'single framework' + $settings.build.output = 'docs-output' + ConvertTo-Json $settings -Depth 5 | Set-Content -LiteralPath $config + & $build -DocfxConfig $config -OutputRoot $output -NoRestore + Test-Path -LiteralPath "$output/net11/docs-output/api/Library.html" | Should -BeTrue + Test-Path -LiteralPath "$output/net10" | Should -BeFalse + Get-Content -LiteralPath "$fixture/dotnet.log" -Raw | Should -Not -Match '(?m)^restore ' + } + + It 'renders with the default destination and metadata when optional keys are absent under StrictMode' { + Set-StrictMode -Version Latest + $scenario = 'single framework' + & $build -DocfxConfig $config -OutputRoot $output + + Test-Path -LiteralPath "$output/net11/_site/api/Library.html" | Should -BeTrue + $metadata = Get-Content -LiteralPath "$output/net11/framework-metadata.json" -Raw | ConvertFrom-Json -AsHashtable + $metadata.metadata[0].properties.Configuration | Should -BeExactly 'Release' + $render = Get-Content -LiteralPath "$output/net11/framework-build.json" -Raw | ConvertFrom-Json -AsHashtable + $render.build.globalMetadata._frameworkDirectory | Should -BeExactly 'net11' + } + + It 'diagnoses ' -ForEach @( + @{ scenario = 'missing CLI'; expected = '*add its executable to PATH*' } + @{ scenario = 'CLI version failure'; expected = '*Could not determine the installed DocFX version*' } + @{ scenario = 'wrong CLI version'; expected = '*found ''2.80.0''*' } + @{ scenario = 'missing store'; expected = '*mapping libraries were not found*' } + @{ scenario = 'missing mapping library'; expected = '*mapping library can be found*' } + @{ scenario = 'missing template entry'; expected = '*Configure one ms-style entry*' } + @{ scenario = 'missing custom template'; expected = '*configured in docfx.json was not found*' } + @{ scenario = 'template inside output'; expected = '*outside the ms-style template directory*' } + @{ scenario = 'stale template contract'; expected = '*framework-views.compat, found ''stale''*' } + @{ scenario = 'missing template contract'; expected = '*framework-views.compat, found missing or empty*' } + @{ scenario = 'missing selector script'; expected = '*Missing public/framework-view.js*' } + @{ scenario = 'invalid output lock'; expected = '*Invalid framework output lock*' } + @{ scenario = 'resolver failure'; expected = '*dotnet exited with 1*discovery.log*' } + @{ scenario = 'assembly input'; expected = '*require project inputs*Library.dll*' } + @{ scenario = 'project inside output'; expected = '*Library.csproj*is inside the framework output*' } + @{ scenario = 'pinned framework'; expected = '*Remove TargetFramework from the properties*' } + @{ scenario = 'MSBuild evaluation failure'; expected = '*MSBuild evaluation failed*Library.csproj*' } + @{ scenario = 'no frameworks'; expected = '*No target frameworks*Library.csproj*' } + @{ scenario = 'conflicting properties'; expected = '*Use the same metadata properties*Library.csproj*' } + @{ scenario = 'empty mapping'; expected = '*No project matched metadata destination*' } + @{ scenario = 'project SDK failure'; expected = '*Could not determine the selected .NET SDK*' } + @{ scenario = 'different shared assets'; expected = '*Cannot share public/shared.js with net-10.0*' } + ) { + switch ($scenario) { + 'missing store' { Rename-Item -LiteralPath "$fixture/.store" -NewName 'unused-store' } + 'missing mapping library' { Remove-Item -LiteralPath "$store/Docfx.Glob.dll" } + 'missing template entry' { $settings.build.template = @('default') } + 'missing custom template' { $settings.build.template = @('custom/ms-style') } + 'template inside output' { + $settings.build.template = @((New-Item -ItemType Directory -Path "$output/ms-style").FullName) + } + { $_ -in 'stale template contract', 'missing template contract', 'missing selector script' } { + $template = (New-Item -ItemType Directory -Path "$fixture/custom/ms-style").FullName + $settings.build.template = @($template) + if ($scenario -eq 'stale template contract') { Set-Content -LiteralPath "$template/framework-views.compat" 'stale' } + if ($scenario -eq 'missing selector script') { + Set-Content -LiteralPath "$template/framework-views.compat" 'framework-views-v1/docfx-2.81.0' + } + } + 'invalid output lock' { New-Item -ItemType Directory -Path "$output/.docfx-framework-views.lock" | Out-Null } + 'pinned framework' { $settings.metadata[0].properties = @{ TargetFramework = 'net11.0' } } + 'conflicting properties' { $settings.metadata += @{ dest = 'api/other'; properties = @{ Configuration = 'Debug' } } } + } + ConvertTo-Json $settings -Depth 5 | Set-Content -LiteralPath $config + { & $build -DocfxConfig $config -OutputRoot $output } | Should -Throw $expected + } +} diff --git a/tests/framework-view/DocfxMetadata.Tests.ps1 b/tests/framework-view/DocfxMetadata.Tests.ps1 new file mode 100644 index 0000000..7fd52b4 --- /dev/null +++ b/tests/framework-view/DocfxMetadata.Tests.ps1 @@ -0,0 +1,233 @@ +BeforeAll { + . "$PSScriptRoot/../../framework-views/FrameworkViewConventions.ps1" + . "$PSScriptRoot/../../framework-views/DocfxMetadata.ps1" + + function Invoke-Step([string] $Log, [string] $Command, [string[]] $Arguments, [switch] $ReturnExitCode) { + throw 'The unit test must provide a tool result.' + } +} + +Describe 'Staged DocFX metadata' { + It 'reads MSBuild JSON even when the SDK prints a banner' { + $output = 'SDK banner', '{', ' "Properties": {"TargetFramework": "net11.0"}', '}' + (Read-MSBuildJson $output 'fixture.csproj').Properties.TargetFramework | Should -BeExactly 'net11.0' + { Read-MSBuildJson @('unexpected output') 'fixture.csproj' } | Should -Throw '*fixture.csproj*unexpected output*' + } + + It 'clears generated metadata and keeps authored documentation' { + $folder = New-Item -ItemType Directory -Path "$TestDrive/stage" + Clear-StagedMetadata "$folder/missing" "$folder/missing/.manifest" + Set-Content -LiteralPath "$folder/toc.yml" -Value '- name: Authored' + Set-Content -LiteralPath "$folder/overwrite.yml" -Value '### YamlMime:ManagedReferenceOverwrite' + Set-Content -LiteralPath "$folder/Api.yml" -Value '### YamlMime:ManagedReference' + Clear-StagedMetadata $folder.FullName "$folder/.manifest" + Test-Path -LiteralPath "$folder/Api.yml" | Should -BeFalse + Test-Path -LiteralPath "$folder/toc.yml" | Should -BeTrue + Set-Content -LiteralPath "$folder/.manifest" -Value '{}' + Set-Content -LiteralPath "$folder/toc.yml" -Value '- name: Generated' + Clear-StagedMetadata $folder.FullName "$folder/.manifest" + Test-Path -LiteralPath "$folder/.manifest" | Should -BeFalse + Test-Path -LiteralPath "$folder/toc.yml" | Should -BeFalse + Test-Path -LiteralPath "$folder/overwrite.yml" | Should -BeTrue + } +} + +Describe 'DocFX project reference recovery' { + BeforeEach { + $project = Join-Path $TestDrive 'project.csproj' + $projects = @{ $project = @{ id = 0; properties = @('-p:Configuration=Release', '-p:AssemblyVersion=3.0.0.0') } } + $group = @{ src = @(@{ src = $TestDrive; files = @('project.csproj') }); properties = @{ AssemblyVersion = '3.0.0.0' } } + $hook = Join-Path $TestDrive 'recovery.targets' + $authoredHook = Join-Path $TestDrive 'authored.targets' + Set-Content -LiteralPath $authoredHook -Value '' + $script:probe = @{ + Properties = @{ CustomAfterMicrosoftCommonTargets = ''; CustomBeforeMicrosoftCommonTargets = ''; ProduceReferenceAssembly = 'false' } + Items = @{ _MSBuildProjectReferenceExistent = @( + @{ ReferenceOutputAssembly = 'true'; NearestTargetFramework = 'netstandard2.0' } + ) } + } + Mock Invoke-Step { + if ($Arguments[0] -eq 'msbuild') { + $script:probe | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $Log + } + } + } + + It 'builds only the affected view and preserves authored version properties' { + Repair-DocfxProjectReferences @($group) $projects 'net11.0' $TestDrive $hook | Should -BeTrue + $group.properties.CustomAfterMicrosoftCommonTargets | Should -BeExactly $hook + $group.properties.AssemblyVersion | Should -BeExactly '3.0.0.0' + Should -Invoke Invoke-Step -Exactly 1 -ParameterFilter { + $Command -eq 'dotnet' -and ($Arguments -join ' ') -like 'build * -f net11.0 --no-restore -p:Configuration=Release -p:AssemblyVersion=3.0.0.0' + } + } + + It 'keeps same-target and build-only references on the ordinary path' { + $script:probe.Items._MSBuildProjectReferenceExistent = @( + @{ ReferenceOutputAssembly = 'true'; NearestTargetFramework = 'net11.0' } + @{ ReferenceOutputAssembly = 'false'; NearestTargetFramework = 'netstandard2.0' } + ) + Repair-DocfxProjectReferences @($group) $projects 'net11.0' $TestDrive $hook | Should -BeFalse + $group.properties.Contains('CustomAfterMicrosoftCommonTargets') | Should -BeFalse + Should -Invoke Invoke-Step -Exactly 0 -ParameterFilter { $Arguments[0] -eq 'build' } + } + + It 'uses reference assemblies for a diagnosed same-target dependency without compiling' { + $dependency = Join-Path $TestDrive 'dependency.csproj' + $script:probe.Items._MSBuildProjectReferenceExistent = @( + @{ ReferenceOutputAssembly = 'true'; NearestTargetFramework = 'netstandard2.0'; FullPath = $dependency } + ) + Repair-DocfxProjectReferences @($group) $projects 'netstandard2.0' $TestDrive $hook @($dependency) | Should -BeTrue + $group.properties.ProduceReferenceAssembly | Should -BeExactly 'true' + $group.properties.Contains('CustomAfterMicrosoftCommonTargets') | Should -BeFalse + Should -Invoke Invoke-Step -Exactly 0 -ParameterFilter { $Arguments[0] -eq 'build' } + } + + It 'leaves unrelated, build-only and explicitly configured same-target references alone' { + $dependency = Join-Path $TestDrive 'dependency.csproj' + $script:probe.Items._MSBuildProjectReferenceExistent = @( + @{ ReferenceOutputAssembly = 'true'; NearestTargetFramework = 'netstandard2.0'; FullPath = $dependency } + @{ ReferenceOutputAssembly = 'false'; NearestTargetFramework = 'netstandard2.0'; FullPath = $project } + ) + Repair-DocfxProjectReferences @($group) $projects 'netstandard2.0' $TestDrive $hook @($project) | Should -BeFalse + $group.properties.ProduceReferenceAssembly = 'false' + Repair-DocfxProjectReferences @($group) $projects 'netstandard2.0' $TestDrive $hook @($dependency) | Should -BeFalse + $group.properties.ProduceReferenceAssembly | Should -BeExactly 'false' + Should -Invoke Invoke-Step -Exactly 0 -ParameterFilter { $Arguments[0] -eq 'build' } + } + + It 'produces reference assemblies during a recovery build when both reference cases occur' { + $dependency = Join-Path $TestDrive 'dependency.csproj' + $script:probe.Items._MSBuildProjectReferenceExistent += @{ + ReferenceOutputAssembly = 'true'; NearestTargetFramework = 'net11.0'; FullPath = $dependency + } + Repair-DocfxProjectReferences @($group) $projects 'net11.0' $TestDrive $hook @($dependency) | Should -BeTrue + $group.properties.ProduceReferenceAssembly | Should -BeExactly 'true' + $group.properties.CustomAfterMicrosoftCommonTargets | Should -BeExactly $hook + Should -Invoke Invoke-Step -Exactly 1 -ParameterFilter { + $Arguments[0] -eq 'build' -and '-p:ProduceReferenceAssembly=true' -cin $Arguments + } + } + + It 'uses the other hook when a consumer already uses the default recovery hook' { + $script:probe.Properties.CustomAfterMicrosoftCommonTargets = $authoredHook + Repair-DocfxProjectReferences @($group) $projects 'net11.0' $TestDrive $hook | Should -BeTrue + $group.properties.Contains('CustomAfterMicrosoftCommonTargets') | Should -BeFalse + $group.properties.CustomBeforeMicrosoftCommonTargets | Should -BeExactly $hook + } + + It 'preserves an explicitly configured hook even when its file does not exist' { + $group.properties.CustomAfterMicrosoftCommonTargets = "$TestDrive/missing.targets" + Repair-DocfxProjectReferences @($group) $projects 'net11.0' $TestDrive $hook | Should -BeTrue + $group.properties.CustomAfterMicrosoftCommonTargets | Should -BeExactly "$TestDrive/missing.targets" + $group.properties.CustomBeforeMicrosoftCommonTargets | Should -BeExactly $hook + } + + It 'diagnoses an affected group with both MSBuild hooks in use' { + $script:probe.Properties.CustomAfterMicrosoftCommonTargets = $authoredHook + $script:probe.Properties.CustomBeforeMicrosoftCommonTargets = $authoredHook + { Repair-DocfxProjectReferences @($group) $projects 'net11.0' $TestDrive $hook } | Should -Throw '*needs an unused*' + Should -Invoke Invoke-Step -Exactly 0 -ParameterFilter { $Arguments[0] -eq 'build' } + } +} + +Describe 'DocFX metadata generation and cache publication' { + BeforeEach { + $root = New-Item -ItemType Directory -Path "$TestDrive/$([guid]::NewGuid())" + $stage = (New-Item -ItemType Directory -Path "$root/net11").FullName + $api = "$stage/api" + $cache = "$root/net11.0.zip" + $group = @{ dest = 'api'; properties = @{ TargetFramework = 'net11.0' } } + Write-Json "$stage/framework-metadata.json" @{ metadata = @($group) } + $script:missingReference = 'Found project reference without a matching metadata reference' + + Mock Repair-DocfxProjectReferences { + $Metadata[0].properties.CustomAfterMicrosoftCommonTargets = $TargetsFile + $true + } + Mock Invoke-Step { + New-Item -ItemType Directory -Path "$stage/api" -Force | Out-Null + if (Test-Path -LiteralPath "$stage/metadata-before-recovery.log") { + Test-Path -LiteralPath "$stage/api/Partial.yml" | Should -BeFalse + (Read-Json $Arguments[1]).metadata[0].properties.CustomAfterMicrosoftCommonTargets | Should -BeExactly 'recovery.targets' + Set-Content -LiteralPath $Log 'warning: missing XML comments' + Set-Content -LiteralPath "$stage/api/Complete.yml" '### YamlMime:ManagedReference' + Write-Json "$stage/api/.manifest" @{ 'Fixture.Common' = 'Complete.yml' } + return 0 + } else { + Set-Content -LiteralPath $Log @("`e[38;5;11mwarning: ${script:missingReference}: $root/dependency.csproj`e[0m", 'error: error CS1704') + Set-Content -LiteralPath "$stage/api/Partial.yml" '### YamlMime:ManagedReference' + Write-Json "$stage/api/.manifest" @{ 'Fixture.Common' = 'Partial.yml' } + return -1 + } + } + } + + It 'recovers a project path from a colorized warning and caches only regenerated metadata' { + New-DocfxMetadata @($group) @{} 'net11.0' 'net-11.0' $stage 'recovery.targets' 'docfx' $cache | Should -Be 1 + Should -Invoke Invoke-Step -Exactly 2 -ParameterFilter { $Command -eq 'docfx' -and $Arguments[0] -eq 'metadata' -and $ReturnExitCode } + Should -Invoke Repair-DocfxProjectReferences -Exactly 1 -ParameterFilter { "$root/dependency.csproj" -cin $MissingProjects } + Get-Content -LiteralPath "$stage/metadata-before-recovery.log" -Raw | Should -Match $script:missingReference + $extracted = "$root/extracted" + [IO.Compression.ZipFile]::ExtractToDirectory($cache, $extracted) + (Get-Content -LiteralPath "$extracted/fingerprint") | Should -BeExactly (Get-MetadataFingerprint @("$extracted/api")) + Test-Path -LiteralPath "$extracted/api/Complete.yml" | Should -BeTrue + Test-Path -LiteralPath "$extracted/api/Partial.yml" | Should -BeFalse + } + + It 'fails if the warning persists and leaves a previously published cache archive intact' { + Mock Invoke-Step { + New-Item -ItemType Directory -Path "$stage/api" -Force | Out-Null + Write-Json "$stage/api/.manifest" @{ 'Fixture.Common' = 'Partial.yml' } + Set-Content -LiteralPath $Log "warning: $script:missingReference" + 0 + } + [IO.Compression.ZipFile]::CreateFromDirectory($stage, $cache) + $hash = (Get-FileHash -LiteralPath $cache).Hash + { New-DocfxMetadata @($group) @{} 'net11.0' 'net-11.0' $stage 'recovery.targets' 'docfx' $cache } | + Should -Throw '*net-11.0*still has unresolved project references after recovery*metadata.log*metadata-before-recovery.log*' + Should -Invoke Invoke-Step -Exactly 2 + (Get-FileHash -LiteralPath $cache).Hash | Should -BeExactly $hash + Test-Path -LiteralPath "$root/generated-net11.0" | Should -BeFalse + } + + It 'fails if the warning cannot be recovered and creates no archive' { + Mock Repair-DocfxProjectReferences { $false } + { New-DocfxMetadata @($group) @{} 'net11.0' 'net-11.0' $stage 'recovery.targets' 'docfx' $cache } | + Should -Throw '*net-11.0*recovery was unavailable*metadata.log*' + Should -Invoke Invoke-Step -Exactly 1 + Test-Path -LiteralPath $cache | Should -BeFalse + } + + It 'accepts ordinary warnings without probing or compiling references' { + Mock Invoke-Step { + New-Item -ItemType Directory -Path "$stage/api" | Out-Null + Write-Json "$stage/api/.manifest" @{ 'Fixture.Common' = 'Complete.yml' } + Set-Content -LiteralPath $Log 'warning: missing XML comments' + 0 + } + New-DocfxMetadata @($group) @{} 'net11.0' 'net-11.0' $stage 'recovery.targets' 'docfx' | Should -Be 1 + Should -Invoke Invoke-Step -Exactly 1 + Should -Invoke Repair-DocfxProjectReferences -Exactly 0 + } + + It 'rejects before publishing an archive' -ForEach @( + @{ reason = 'a logged error'; exitCode = 0; message = 'error: failed generation'; manifest = $null; expected = '*metadata failed*metadata.log*' } + @{ reason = 'a colorized error'; exitCode = 0; message = "`e[38;5;9merror: failed generation`e[0m"; manifest = $null; expected = '*metadata failed*metadata.log*' } + @{ reason = 'a failed exit code'; exitCode = 1; message = ''; manifest = $null; expected = '*metadata failed*metadata.log*' } + @{ reason = 'a missing manifest'; exitCode = 0; message = 'warning: missing XML comments'; manifest = $null; expected = '*Incomplete metadata*metadata.log*' } + @{ reason = 'an empty manifest'; exitCode = 0; message = 'warning: missing XML comments'; manifest = @{}; expected = '*Empty DocFX metadata*net-11.0*' } + ) { + Mock Invoke-Step { + if ($null -ne $manifest) { + New-Item -ItemType Directory -Path "$stage/api" | Out-Null + Write-Json "$stage/api/.manifest" $manifest + } + Set-Content -LiteralPath $Log $message + $exitCode + } + { New-DocfxMetadata @($group) @{} 'net11.0' 'net-11.0' $stage 'recovery.targets' 'docfx' $cache } | Should -Throw $expected + Should -Invoke Repair-DocfxProjectReferences -Exactly 0 + Test-Path -LiteralPath $cache | Should -BeFalse + } +} diff --git a/tests/framework-view/FrameworkViewConventions.Tests.ps1 b/tests/framework-view/FrameworkViewConventions.Tests.ps1 new file mode 100644 index 0000000..9eddc9b --- /dev/null +++ b/tests/framework-view/FrameworkViewConventions.Tests.ps1 @@ -0,0 +1,94 @@ +BeforeAll { + . "$PSScriptRoot/../../framework-views/FrameworkViewConventions.ps1" +} + +Describe 'Framework view conventions' { + It 'derives the deepest common API directory by whole segments' { + Get-ApiPath @(@{ dest = 'api/dotnet/runtime/v2' }, @{ dest = 'api/dotnet/utility' }) | Should -BeExactly 'api/dotnet' + Get-ApiPath @(@{ dest = 'api/dotnet' }, @{ dest = 'api/dotnet/utility' }) | Should -BeExactly 'api/dotnet' + Get-ApiPath @(@{ dest = 'api/dotnet' }) | Should -BeExactly 'api/dotnet' + } + + It 'rejects missing, malformed, disjoint and reserved destinations' { + { Get-ApiPath @() } | Should -Throw '*metadata group*' + foreach ($dest in $null, 1, '/api', '../api', 'api\dotnet', 'api//other', 'api/../other', 'api/', "api`n") { + { Get-ApiPath @(@{ dest = $dest }) } | Should -Throw '*metadata.dest*' + } + foreach ($pair in @(@('api', 'apis/view'), @('api/sub', 'API/sub'))) { + { Get-ApiPath @(@{ dest = $pair[0] }, @{ dest = $pair[1] }) } | Should -Throw '*no common API directory*' + } + { Get-ApiPath @(@{ dest = '_frameworks/api' }) } | Should -Throw '*reserved directory*' + } + + It 'orders framework families and numeric versions independently of discovery order' { + $expected = 'net105.0', 'net11.10', 'net11.9', 'net11.0', 'net10.0', 'net9.0', + 'netcoreapp3.1', 'netcoreapp2.10', 'netcoreapp2.9', 'netstandard2.1', 'netstandard2.0', 'net481', 'net48', 'net462' + $frameworks = foreach ($tfm in $expected[($expected.Count - 1)..0]) { Get-FrameworkView $tfm 'test.csproj' } + $ordered = @(Get-OrderedFrameworkViews ($frameworks + $frameworks[0])) + ($ordered.tfm -join ',') | Should -BeExactly ($expected -join ',') + $ordered[0].directory | Should -BeExactly 'net105' + $ordered[0].view | Should -BeExactly 'net-105.0' + $ordered[1].directory | Should -BeExactly 'net11.10' + $ordered[-1].view | Should -BeExactly 'net462' + } + + It 'diagnoses unsupported targets with their project' { + foreach ($tfm in 'net11.0-windows', 'net11.0-android', 'uap10.0', 'net0.0', 'net5', 'net999999999999.0') { + { Get-FrameworkView $tfm 'test.csproj' } | Should -Throw "*'$tfm'*'test.csproj'*" + } + } + + It 'preserves the public mapping of dotted .NET Framework targets' { + $dotted = Get-FrameworkView 'net4.8' 'test.csproj' + $compact = Get-FrameworkView 'net48' 'test.csproj' + $dotted.family | Should -Be $compact.family + $dotted.version | Should -Be $compact.version + $dotted.view | Should -BeExactly 'net-4.8' + $dotted.directory | Should -BeExactly 'net4.8' + } +} + +Describe 'Output ownership and path isolation' { + It 'compares full path segments and includes the directory itself' { + Test-PathWithin "$TestDrive/build" "$TestDrive/build" | Should -BeTrue + Test-PathWithin "$TestDrive/build" "$TestDrive/build/site" | Should -BeTrue + Test-PathWithin "$TestDrive/build" "$TestDrive/build-cache" | Should -BeFalse + Test-PathWithin "$TestDrive/build" $TestDrive | Should -BeFalse + } + + It 'rejects a file or symlink in the output path' { + $directory = New-Item -ItemType Directory -Path "$TestDrive/target" + $linkType = if ($IsWindows) { 'Junction' } else { 'SymbolicLink' } + New-Item -ItemType $linkType -Path "$TestDrive/alias" -Target $directory.FullName | Out-Null + Set-Content -LiteralPath "$TestDrive/file" -Value 'file' + { Assert-SafeOutputPath "$TestDrive/target/new" } | Should -Not -Throw + { Assert-SafeOutputPath "$TestDrive/file" } | Should -Throw '*file or link*' + { Assert-SafeOutputPath "$TestDrive/alias/new" } | Should -Throw '*file or link*' + } + + It 'accepts empty output and identifies owned entries only' { + $root = New-Item -ItemType Directory -Path "$TestDrive/output" + @(Get-FrameworkOutputEntries $root.FullName '.owner' '.lock').Count | Should -Be 0 + Set-Content -LiteralPath "$root/.owner" -Value @('docfx-framework-views-v1', 'site') + Set-Content -LiteralPath "$root/.lock" -Value '' + New-Item -ItemType Directory -Path "$root/site" | Out-Null + @(Get-FrameworkOutputEntries $root.FullName '.owner' '.lock').Name | Should -BeExactly 'site' + } + + It 'refuses unowned directories, unexpected entries and nested links before cleanup' { + $root = New-Item -ItemType Directory -Path "$TestDrive/disputed" + Set-Content -LiteralPath "$root/sentinel" -Value 'authored' + { Get-FrameworkOutputEntries $root.FullName '.owner' '.lock' } | Should -Throw '*empty or owned*' + Set-Content -LiteralPath "$root/.owner" -Value 'invalid' + { Get-FrameworkOutputEntries $root.FullName '.owner' '.lock' } | Should -Throw '*empty or owned*' + Set-Content -LiteralPath "$root/.owner" -Value @('docfx-framework-views-v1', 'site') + { Get-FrameworkOutputEntries $root.FullName '.owner' '.lock' } | Should -Throw '*Unexpected item*sentinel*' + Get-Content -LiteralPath "$root/sentinel" | Should -BeExactly 'authored' + Set-Content -LiteralPath "$root/.owner" -Value @('docfx-framework-views-v1', 'site', 'sentinel') + $directory = New-Item -ItemType Directory -Path "$TestDrive/outside" + New-Item -ItemType Directory -Path "$root/site" | Out-Null + $linkType = if ($IsWindows) { 'Junction' } else { 'SymbolicLink' } + New-Item -ItemType $linkType -Path "$root/site/linked" -Target $directory.FullName | Out-Null + { Get-FrameworkOutputEntries $root.FullName '.owner' '.lock' } | Should -Throw '*contains a link*' + } +} diff --git a/tests/framework-view/README.md b/tests/framework-view/README.md index 2ec0d63..e81e48f 100644 --- a/tests/framework-view/README.md +++ b/tests/framework-view/README.md @@ -4,6 +4,20 @@ All suites use the [framework views generator in this repository](../../framewor Use PowerShell 7 on the host. The native and browser suites also require the .NET 11 SDK and DocFX CLI 2.81.0 on the host PATH. Install .NET 8 side by side for the older SDK test. For HTTP tests, use Docker in Linux-container mode. The browser tests also require Node.js 20 or newer and Chromium. +## Unit tests and coverage + +Run with Pester 5. Measure all three PowerShell implementation files so the report includes the generator entry point. The unit tests exercise preflight checks, framework conventions, output ownership, and metadata recovery and publication with the external commands mocked. The native and packaged suites below exercise real project discovery, MSBuild, DocFX, cache reuse, rendering and packaging. + +```powershell +$configuration = New-PesterConfiguration +$configuration.Run.Path = 'tests/framework-view/*.Tests.ps1' +$configuration.CodeCoverage.Enabled = $true +$configuration.CodeCoverage.Path = (Get-ChildItem framework-views/*.ps1).FullName +$configuration.CodeCoverage.OutputPath = Join-Path ([IO.Path]::GetTempPath()) 'docfx-framework-views-unit.xml' +$configuration.CodeCoverage.CoveragePercentTarget = 100 +Invoke-Pester -Configuration $configuration +``` + ## Native generation and HTTP routing ```powershell @@ -11,7 +25,7 @@ pwsh -NoProfile -File tests/framework-view/Test-FrameworkViews.ps1 -TestRouting pwsh -NoProfile -File tests/framework-view/Test-FrameworkViews.ps1 -ProjectSdk8 -TestRouting ``` -These exercise glob exclusions, nested metadata destinations, per-view project availability, cache reuse, invalidation and isolated recovery. The second command selects .NET 8 for the projects and a modern SDK for the resolver. Without `-TestRouting`, the suite runs without Docker on Windows, Linux or CI. +These exercise glob exclusions, nested metadata destinations, per-view project availability, full assembly identities, inherited overloads, consumer MSBuild hooks, repeat builds, cache reuse, invalidation and isolated recovery. The second command selects .NET 8 for the projects and a modern SDK for the resolver. Without `-TestRouting`, the suite runs without Docker on Windows, Linux or CI. ## Packaged builder and browser regression @@ -21,7 +35,7 @@ Two fixture projects document `/api/runtime/` and `/api/utilities/`. Conditional pwsh -NoProfile -File tests/framework-view/Test-FrameworkView.ps1 -ContainerOnly ``` -The complete suite also tests the host generator with the image providing rendering. It serves that output and an ordinary single-framework site with the shared NGINX Dockerfile. The browser checks cover the selector, UID and fragment resolution, fallback, direct URLs, navigation, search, and mobile keyboard operation. +The complete suite also runs the generator natively and compares the runtime manifest and routing with the container build. It serves the native output and an ordinary single-framework site with the shared NGINX Dockerfile. The browser checks cover the selector, UID and fragment resolution, fallback, direct URLs, navigation, search, and mobile keyboard operation. ```powershell Push-Location tests/framework-view @@ -31,11 +45,11 @@ Pop-Location pwsh -File tests/framework-view/Test-FrameworkView.ps1 ``` -On Linux, install Chromium's system dependencies with `npx playwright install --with-deps chromium` if needed. Use `-SkipImageBuild -BuilderImage ` to test an existing builder image. Registry publication and post-publish verification require release approval and registry access. See the [release procedure](../../README.md#publish-and-verify-the-builder-image). +On Linux, install Chromium's system dependencies with `npx playwright install --with-deps chromium` if needed. Use `-SkipImageBuild -BuilderImage ` to test an existing builder image. For CI-aligned native builder image validation (including OCI labels, architecture, SDKs, PowerShell 7, complete `/opt/docfx/framework-views` distribution, multi-framework build, and single-framework build), run `pwsh -NoProfile -File tests/Test-DocfxContainer.ps1 -Image -Platform linux/amd64`. Official production publication uses the build-once GitHub Actions release and deployment lifecycle described in [CI/CD release and deployment lifecycle](../../README.md#cicd-release-and-deployment-lifecycle). ## Cuemon.Kernel and Cuemon.IO -The test uses the authored Cuemon project mappings, filter, overwrites, template, and run actions from the [fixture revision](https://github.com/codebeltnet/cuemon/tree/53875b1bbb778067a0a029b87861efdb0b78a8b5). It stages a two-project configuration in the consumer checkout and enables assembly-version alignment for the mixed target graph. Run on Windows or Linux with Git and the native prerequisites above. +The test uses the authored Cuemon project mappings, filter, overwrites, template, and run actions from the [fixture revision](https://github.com/codebeltnet/cuemon/tree/53875b1bbb778067a0a029b87861efdb0b78a8b5). It stages a two-project configuration in the consumer checkout and exercises the generator's cross-target reference recovery. Run on Windows or Linux with Git and the native prerequisites above. ```powershell $scratch = Join-Path ([IO.Path]::GetTempPath()) "docfx-cuemon-$([guid]::NewGuid().ToString('N'))" @@ -47,4 +61,4 @@ pwsh -NoProfile -File tests/framework-view/cuemon/Build-CuemonFixture.ps1 -Consu pwsh -NoProfile -File tests/framework-view/cuemon/Test-CuemonFrameworkViews.ps1 -Workspace $output ``` -The acceptance test checks the native xref inventory against every served API and fragment, framework-specific TOCs and search, overload and inheritance differences, source and run-action links, overwrite examples, and HTTP caching. It expects 557, 557, 76 and 548 metadata UIDs in framework order. Pass `-BuilderImage ` to the fixture build to render in the container, or `-Origin ` to the acceptance test to check an already running server. +The acceptance test checks the native xref inventory against every served API and fragment, framework-specific TOCs and search, overload and inheritance differences, source and run-action links, overwrite examples, and HTTP caching. It expects 557, 557, 76 and 548 metadata UIDs in framework order. To use the builder image, run the entire fixture build in the container with the test scripts and a writable fixture checkout mounted. Pass `-Origin ` to the acceptance test to check an already running server. diff --git a/tests/framework-view/Test-FrameworkView.ps1 b/tests/framework-view/Test-FrameworkView.ps1 index 04b3d41..6d927ef 100644 --- a/tests/framework-view/Test-FrameworkView.ps1 +++ b/tests/framework-view/Test-FrameworkView.ps1 @@ -15,32 +15,36 @@ $output = "$work/output" $container = $null $previousOrigin = $env:DOCFX_TEST_ORIGIN +function Copy-Fixture([string] $Destination) { + Copy-Item -LiteralPath "$PSScriptRoot/fixture" -Destination $Destination -Recurse + $docs = New-Item -ItemType Directory -Path "$Destination/.docfx" + Move-Item -LiteralPath "$Destination/docfx.json", "$Destination/index.md", "$Destination/toc.yml" -Destination $docs.FullName +} + function Test-PackagedGenerator { $fixture = "$work/container-fixture" - $destination = "$work/container-output" - Copy-Item -LiteralPath "$PSScriptRoot/fixture" -Destination $fixture -Recurse - @{ apiPath = 'api'; defaultFramework = 'net11.0' } | - ConvertTo-Json | Set-Content -LiteralPath "$fixture/framework-views.json" + $destination = "$fixture/.bot/docfx" + Copy-Fixture $fixture New-Item -ItemType Directory -Path "$work/sdk10" | Out-Null '{"sdk":{"version":"10.0.100","rollForward":"latestFeature"}}' | Set-Content -LiteralPath "$work/sdk10/global.json" '{"sdk":{"version":"11.0.100","rollForward":"latestFeature"}}' | Set-Content -LiteralPath "$fixture/global.json" $mount = "type=bind,source=$work,target=/workspace" + Import-Module "$repo/tools/DocfxImage.psm1" + $expectedDocfx = Get-DocfxDefaultVersion -RootPath $repo $pwshVersion = docker run --rm $BuilderImage pwsh -NoProfile -Command '$PSVersionTable.PSVersion.ToString()' $docfxVersion = docker run --rm $BuilderImage docfx --version $sdk10 = @(docker run --rm --mount $mount -w /workspace/sdk10 $BuilderImage sh -ec 'dotnet --version && dotnet msbuild -nologo -version') $sdk11 = docker run --rm --mount $mount -w /workspace/container-fixture $BuilderImage dotnet --version - if ($pwshVersion -notmatch '^7\.' -or $docfxVersion -notmatch '^2\.81\.0(?:\+.+)?$' -or + if ($pwshVersion -notmatch '^7\.' -or $docfxVersion -notmatch "^$([regex]::Escape($expectedDocfx))(?:\+.+)?$" -or $sdk10[0] -notmatch '^10\.' -or $sdk11 -notmatch '^11\.') { throw "Unexpected builder toolchain. PowerShell: $pwshVersion. DocFX: $docfxVersion. SDKs: $($sdk10[0]), $sdk11." } Write-Host "Packaged tools: PowerShell $pwshVersion, DocFX $docfxVersion, .NET $($sdk10[0]) and $sdk11." - $generatorArguments = @( - '-DocfxConfig', 'container-fixture/docfx.json' - '-SettingsPath', 'container-fixture/framework-views.json' - '-OutputRoot', 'container-output' - ) - docker run --rm --mount $mount -w /workspace $BuilderImage pwsh -NoProfile -File /opt/docfx/framework-views/Build-DocfxFrameworkViews.ps1 @generatorArguments + docker run --rm --mount $mount -w /workspace/container-fixture $BuilderImage pwsh -NoProfile -File /opt/docfx/framework-views/Build-DocfxFrameworkViews.ps1 + if (Get-ChildItem -LiteralPath $destination -Filter 'build-*.log' -Recurse) { + throw 'Ordinary metadata generation ran a recovery compilation.' + } foreach ($project in 'Runtime', 'Utilities') { if (!(Test-Path -LiteralPath "$fixture/$project/obj/project.assets.json" -PathType Leaf)) { @@ -102,24 +106,23 @@ try { Test-PackagedGenerator if ($ContainerOnly) { return } - Copy-Item -LiteralPath "$PSScriptRoot/fixture" -Destination "$work/fixture" -Recurse - @{ - apiPath = 'api' - defaultFramework = 'net11.0' - builderImage = $BuilderImage - } | ConvertTo-Json | Set-Content -LiteralPath "$work/fixture/framework-views.json" - - & "$repo/framework-views/Build-DocfxFrameworkViews.ps1" -DocfxConfig "$work/fixture/docfx.json" ` - -SettingsPath "$work/fixture/framework-views.json" -OutputRoot $output + Copy-Fixture "$work/fixture" + $docs = "$work/fixture/.docfx" + & "$repo/framework-views/Build-DocfxFrameworkViews.ps1" -DocfxConfig "$docs/docfx.json" -OutputRoot $output + foreach ($path in 'site/framework-views.json', 'nginx.conf') { + $native = (Get-Content -LiteralPath "$output/$path" -Raw).Replace("`r`n", "`n") + $packaged = (Get-Content -LiteralPath "$work/container-fixture/.bot/docfx/$path" -Raw).Replace("`r`n", "`n") + if ($native -cne $packaged) { throw "Native and packaged generation differ for '$path'." } + } # Reuse the native .NET 10 metadata to render an ordinary site with the packaged template. $single = "$work/single" New-Item -ItemType Directory -Path $single | Out-Null - Copy-Item -LiteralPath "$output/net10/api", "$work/fixture/index.md", "$work/fixture/toc.yml" -Destination $single -Recurse - $build = (Get-Content -LiteralPath "$work/fixture/docfx.json" -Raw | ConvertFrom-Json -AsHashtable).build + Copy-Item -LiteralPath "$output/net10/api", "$docs/index.md", "$docs/toc.yml" -Destination $single -Recurse + $build = (Get-Content -LiteralPath "$docs/docfx.json" -Raw | ConvertFrom-Json -AsHashtable).build $build.template[2] = '/opt/docfx/templates/ms-style' @{ build = $build } | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath "$single/docfx.json" - docker run --rm --mount "type=bind,source=$single,target=/stage" -w /stage $BuilderImage docfx build docfx.json --warningsAsErrors + docker run --rm --mount "type=bind,source=$single,target=/stage" -w /stage $BuilderImage docfx build docfx.json Copy-Item -LiteralPath "$single/_site" -Destination "$output/site/single" -Recurse $imageContext = "$work/image" diff --git a/tests/framework-view/Test-FrameworkViews.ps1 b/tests/framework-view/Test-FrameworkViews.ps1 index 9862712..d86fdcc 100644 --- a/tests/framework-view/Test-FrameworkViews.ps1 +++ b/tests/framework-view/Test-FrameworkViews.ps1 @@ -8,22 +8,20 @@ param( $ErrorActionPreference = 'Stop' $root = Join-Path ([IO.Path]::GetTempPath()) "docfx-framework-test-$([guid]::NewGuid().ToString('N'))" -$docs = "$root/docs" +$docs = "$root/.docfx" $config = "$docs/docfx.json" $build = "$PSScriptRoot/../../framework-views/Build-DocfxFrameworkViews.ps1" $defaultTfm, $otherTfm = if ($ProjectSdk8) { 'net8.0', 'netstandard2.1' } else { 'net11.0', 'net10.0' } $defaultView, $otherView = $defaultTfm, $otherTfm -creplace '^(net(?:standard)?)(\d)', '$1-$2' $defaultDirectory = $defaultTfm -replace '\.0$', '' $otherDirectory = $otherTfm -replace '\.0$', '' -$settings = "$docs/framework-views.json" $arguments = @{ DocfxConfig = $config - SettingsPath = $settings MetadataCache = "$root/cache" MetadataCacheKey = 'synthetic-regression' } -New-Item -ItemType Directory "$root/src/Runtime", "$root/src/Legacy", "$root/src/Excluded", $docs | Out-Null +New-Item -ItemType Directory "$root/src/Runtime", "$root/src/Legacy", "$root/src/Excluded", "$root/dependencies/Bridge", "$root/dependencies/Model", $docs | Out-Null @' @@ -31,6 +29,11 @@ New-Item -ItemType Directory "$root/src/Runtime", "$root/src/Legacy", "$root/src '@ | Set-Content -LiteralPath "$root/Directory.Build.targets" +@' + + $(DefineConstants);CONSUMER_HOOK + +'@ | Set-Content -LiteralPath "$root/Consumer.targets" if ($ProjectSdk8) { Set-Content "$root/global.json" '{"sdk":{"version":"8.0.100","rollForward":"latestFeature"}}' @@ -43,21 +46,47 @@ if ($ProjectSdk8) { } } $constant = $defaultTfm.ToUpperInvariant().Replace('.', '_') -Set-Content "$root/src/Runtime/Runtime.csproj" "$defaultTfm;$otherTfmlatest" +Set-Content "$root/src/Runtime/Runtime.csproj" @" + + + $otherTfm;$defaultTfm + latest + 3.0.0.0 + + + +"@ Set-Content "$root/src/Runtime/Runtime.cs" @" namespace FrameworkFixture; -public class Common { } -#if $constant +public class Common : Compatibility.Bridge { } +#if $constant && CONSUMER_HOOK public class Modern { } #endif "@ +foreach ($dependency in 'Bridge', 'Model') { + $assemblyVersion = if ($dependency -eq 'Bridge') { '7.1.0.0' } else { '12.2.0.0' } + $projectReference = if ($dependency -eq 'Bridge') { '' } + Set-Content "$root/dependencies/$dependency/$dependency.csproj" @" + + + netstandard2.0 + latest + $assemblyVersion + + $projectReference + +"@ +} +Set-Content "$root/dependencies/Bridge/Bridge.cs" 'namespace FrameworkFixture.Compatibility; public class Bridge : Model { }' +Set-Content "$root/dependencies/Model/Model.cs" 'namespace FrameworkFixture.Compatibility; public class Model { public void InheritedFromModel() { } public void InheritedFromModel(int value) { } }' Set-Content "$root/src/Legacy/Legacy.csproj" "$otherTfmlatest" Set-Content "$root/src/Legacy/Legacy.cs" 'namespace FrameworkFixture.Compatibility; public class Legacy { }' Set-Content "$root/src/Excluded/Excluded.csproj" 'This project must be excluded by the DocFX mapping.' Set-Content "$docs/index.md" '# Shared concept' @{ metadata = @( - @{ src = @(@{ src = '../src'; files = @('**.csproj'); exclude = @('Excluded/**', 'Legacy/**') }); dest = 'reference/runtime' } + @{ src = @(@{ src = '../src'; files = @('**.csproj'); exclude = @('Excluded/**', 'Legacy/**') }); dest = 'reference/runtime' + properties = @{ CustomAfterMicrosoftCommonTargets = "$root/Consumer.targets" } } @{ src = @{ src = '../src'; files = 'Legacy/Legacy.csproj' }; dest = 'reference/legacy' } ) build = @{ @@ -67,23 +96,18 @@ Set-Content "$docs/index.md" '# Shared concept' dest = 'rendered' } } | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $config -@{ apiPath = 'reference'; defaultFramework = $defaultTfm } | - ConvertTo-Json | Set-Content -LiteralPath $settings - if (!$ProjectSdk8) { $sourceTemplate = "$PSScriptRoot/../../templates/ms-style" - $override = "$root/ms-style-override" + $override = "$docs/templates/ms-style" + New-Item -ItemType Directory -Path "$docs/templates" | Out-Null Copy-Item -LiteralPath $sourceTemplate -Destination $override -Recurse - $overrideSettings = "$docs/framework-views-override.json" - @{ apiPath = 'reference'; defaultFramework = $defaultTfm; templatePath = '../ms-style-override' } | - ConvertTo-Json | Set-Content -LiteralPath $overrideSettings $marker = "$override/framework-views.compat" $invalidContracts = @{ stale = 'framework-views-v0/docfx-2.81.0'; empty = '' } foreach ($state in $invalidContracts.Keys) { [IO.File]::WriteAllText($marker, $invalidContracts[$state]) $invalidOutput = "$root/incompatible-$state" try { - & $build -DocfxConfig $config -SettingsPath $overrideSettings -OutputRoot $invalidOutput + & $build -DocfxConfig $config -OutputRoot $invalidOutput throw "A template override with a $state marker was accepted." } catch { if ($_.Exception.Message -notlike 'Incompatible ms-style template*framework-views.compat*') { throw } @@ -91,18 +115,48 @@ if (!$ProjectSdk8) { if (Test-Path -LiteralPath "$invalidOutput/discovery.log") { throw 'Discovery ran before template validation.' } } Copy-Item -LiteralPath "$sourceTemplate/framework-views.compat" -Destination $marker -Force - $arguments.SettingsPath = $overrideSettings Write-Host 'Template overrides with stale and empty markers were rejected before discovery.' } -& $build @arguments -OutputRoot "$root/fresh" -$arguments.SettingsPath = $settings -if ($ProjectSdk8 -and [version](Get-Content -LiteralPath "$root/fresh/resolver-sdk.log" -Raw).Trim().Split('-')[0] -lt [version]'10.0') { +$fresh = "$root/.bot/docfx" +New-Item -ItemType Directory -Path "$root/.bot" | Out-Null +Set-Content -LiteralPath "$root/.bot/keep.txt" 'unrelated artifact' +Push-Location $root +try { + & $build -MetadataCache "$root/cache" -MetadataCacheKey $arguments.MetadataCacheKey +} finally { + Pop-Location +} +if ($ProjectSdk8 -and [version](Get-Content -LiteralPath "$fresh/resolver-sdk.log" -Raw).Trim().Split('-')[0] -lt [version]'10.0') { throw 'The resolver did not select a modern SDK independently of the project pin.' } -$site = "$root/fresh/site" +$site = "$fresh/site" $manifest = Get-Content "$site/framework-views.json" -Raw | ConvertFrom-Json -if (($manifest.viewOrder -join ',') -cne "$defaultView,$otherView") { throw 'Discovered order was not preserved.' } +if (($manifest.viewOrder -join ',') -cne "$defaultView,$otherView" -or $manifest.defaultView -cne $defaultView -or $manifest.apiPath -cne '/reference/') { + throw 'The generated manifest does not reflect the inferred API root and framework precedence.' +} +foreach ($assembly in @( + @{ path = "$root/src/Runtime/bin/Release/$defaultTfm/Runtime.dll"; identity = 'Runtime, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null' } + @{ path = "$root/dependencies/Bridge/bin/Release/netstandard2.0/Bridge.dll"; identity = 'Bridge, Version=7.1.0.0, Culture=neutral, PublicKeyToken=null' } + @{ path = "$root/dependencies/Model/bin/Release/netstandard2.0/Model.dll"; identity = 'Model, Version=12.2.0.0, Culture=neutral, PublicKeyToken=null' } +)) { + if ([Reflection.AssemblyName]::GetAssemblyName($assembly.path).FullName -cne $assembly.identity) { + throw "Cross-target metadata generation changed the assembly identity of '$($assembly.path)'." + } +} +foreach ($directory in $defaultDirectory, $otherDirectory) { + $metadata = Get-Content -LiteralPath "$fresh/$directory/framework-metadata.json" -Raw | ConvertFrom-Json -AsHashtable + $common = "$fresh/$directory/reference/runtime/FrameworkFixture.Common.yml" + if ($metadata.metadata[0].properties.Contains('AssemblyVersion') -or + !(Select-String -LiteralPath $common -Pattern '^\s*- FrameworkFixture\.Compatibility\.Model\.InheritedFromModel$' -Quiet) -or + !(Select-String -LiteralPath $common -Pattern '^\s*- FrameworkFixture\.Compatibility\.Model\.InheritedFromModel\(System\.Int32\)$' -Quiet)) { + throw "Cross-target metadata for '$directory' lost the native dependency identity or inherited API." + } + if ($metadata.metadata[0].properties.CustomAfterMicrosoftCommonTargets -cne "$root/Consumer.targets" -or + (Split-Path -Leaf $metadata.metadata[0].properties.CustomBeforeMicrosoftCommonTargets) -cne 'KeepCrossTargetReferences.targets') { + throw "Cross-target recovery for '$directory' did not preserve the consumer's MSBuild hook." + } +} foreach ($path in 'index.html', 'reference/runtime/FrameworkFixture.Modern.html', "_frameworks/$otherDirectory/reference/legacy/FrameworkFixture.Compatibility.Legacy.html", "_frameworks/$otherDirectory/reference/runtime/FrameworkFixture.Common.html", "_frameworks/$otherDirectory/index.json") { if (!(Test-Path -LiteralPath "$site/$path" -PathType Leaf)) { throw "Missing '$path'." } } @@ -110,13 +164,20 @@ foreach ($path in 'reference/legacy/FrameworkFixture.Compatibility.Legacy.html', if (Test-Path -LiteralPath "$site/$path") { throw "Unexpected '$path'." } } -& $build @arguments -OutputRoot "$root/cached" -if (Get-ChildItem -LiteralPath "$root/cached" -Filter metadata.log -Recurse) { throw 'The second build did not reuse all metadata.' } +$expectedHashes = @{} foreach ($path in 'xrefmap.yml', "_frameworks/$otherDirectory/xrefmap.yml", 'framework-views.json') { - if ((Get-FileHash -LiteralPath "$site/$path").Hash -cne (Get-FileHash -LiteralPath "$root/cached/site/$path").Hash) { + $expectedHashes[$path] = (Get-FileHash -LiteralPath "$site/$path").Hash +} +& $build @arguments -OutputRoot $fresh +if (Get-ChildItem -LiteralPath $fresh -Filter metadata.log -Recurse) { throw 'The second build did not reuse all metadata.' } +foreach ($path in $expectedHashes.Keys) { + if ((Get-FileHash -LiteralPath "$site/$path").Hash -cne $expectedHashes[$path]) { throw "Cached and fresh output differ for '$path'." } } +if ((Get-Content -LiteralPath "$root/.bot/keep.txt") -cne 'unrelated artifact' -or (Test-Path "$docs/framework-views.json")) { + throw 'Rebuilding changed unrelated artifacts or authored configuration.' +} Set-Content -LiteralPath (Get-ChildItem -LiteralPath "$root/cache" -Filter "$defaultTfm.zip" -Recurse).FullName 'invalid cache' & $build @arguments -OutputRoot "$root/recovered" @@ -139,8 +200,8 @@ if ($TestRouting) { Set-Content "$site/_frameworks/$otherDirectory/reference/runtime/index.html" 'other API index' Set-Content "$site/_frameworks/$otherDirectory/reference/legacy/index.html" 'other legacy index' $mounts = @('--mount', "type=bind,source=$site,target=/usr/share/nginx/html,readonly", - '--mount', "type=bind,source=$root/fresh/nginx.conf,target=/etc/nginx/conf.d/default.conf,readonly") - & docker run --rm @mounts $NginxImage -t + '--mount', "type=bind,source=$fresh/nginx.conf,target=/etc/nginx/conf.d/default.conf,readonly") + & docker run --rm --entrypoint nginx @mounts $NginxImage -t if ($LASTEXITCODE -ne 0) { throw 'Generated NGINX configuration is invalid.' } $container = & docker run --rm -d -p 127.0.0.1::8080 @mounts $NginxImage if ($LASTEXITCODE -ne 0) { throw 'Could not start NGINX for routing checks.' } @@ -161,7 +222,8 @@ if ($TestRouting) { foreach ($expected in $responses) { $result = Invoke-WebRequest "http://$endpoint$($expected.path)" -SkipHttpErrorCheck -MaximumRedirection 0 $body = if ($result.Content -is [byte[]]) { [Text.Encoding]::UTF8.GetString($result.Content) } else { $result.Content } - if ($result.StatusCode -ne $expected.status -or ($expected.body -and !$body.Contains($expected.body)) -or + $expectedBody = $expected['body'] + if ($result.StatusCode -ne $expected.status -or ($expectedBody -and !$body.Contains($expectedBody)) -or $result.Headers['Cache-Control'] -notlike '*no-store*' -or $result.Headers['ETag']) { throw "Unexpected routing or caching for '$($expected.path)' (HTTP $($result.StatusCode))." } diff --git a/tests/framework-view/cuemon/Build-CuemonFixture.ps1 b/tests/framework-view/cuemon/Build-CuemonFixture.ps1 index 5317f4f..9cd2501 100644 --- a/tests/framework-view/cuemon/Build-CuemonFixture.ps1 +++ b/tests/framework-view/cuemon/Build-CuemonFixture.ps1 @@ -3,7 +3,6 @@ param( [Parameter(Mandatory)][string] $ConsumerRoot, [Parameter(Mandatory)][string] $OutputRoot, - [string] $BuilderImage, [string] $MetadataCache, [string] $MetadataCacheKey, [switch] $ForceMetadata @@ -44,16 +43,8 @@ try { '@ | Set-Content -LiteralPath "$inputRoot/toc.yml" ConvertTo-Json -InputObject $config -Depth 100 | Set-Content -LiteralPath "$inputRoot/docfx.json" & "$source/BuildRunActions.ps1" -OutputRoot "$inputRoot/run-actions" - $settings = @{ - apiPath = $group[0].dest - defaultFramework = 'net11.0' - frameworks = @('net11.0', 'net10.0', 'netstandard2.1', 'netstandard2.0') - alignAssemblyVersion = $true - } - if ($BuilderImage) { $settings.builderImage = $BuilderImage } - $settings | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath "$inputRoot/framework-views.json" & "$PSScriptRoot/../../../framework-views/Build-DocfxFrameworkViews.ps1" ` - -DocfxConfig "$inputRoot/docfx.json" -SettingsPath "$inputRoot/framework-views.json" -OutputRoot $OutputRoot ` + -DocfxConfig "$inputRoot/docfx.json" -OutputRoot $OutputRoot ` -MetadataCache $MetadataCache -MetadataCacheKey $MetadataCacheKey -ForceMetadata:$ForceMetadata & "$source/TestRunActions.ps1" -ScriptsRoot "$inputRoot/run-actions" -SiteRoot (Join-Path $OutputRoot 'site') } finally { diff --git a/tests/framework-view/fixture/docfx.json b/tests/framework-view/fixture/docfx.json index 6ede304..dbb1cff 100644 --- a/tests/framework-view/fixture/docfx.json +++ b/tests/framework-view/fixture/docfx.json @@ -1,12 +1,12 @@ { "metadata": [ { - "src": [{ "files": ["Runtime/Runtime.csproj"] }], + "src": [{ "src": "..", "files": ["Runtime/Runtime.csproj"] }], "dest": "api/runtime", "memberLayout": "separatePages" }, { - "src": [{ "files": ["Utilities/Utilities.csproj"] }], + "src": [{ "src": "..", "files": ["Utilities/Utilities.csproj"] }], "dest": "api/utilities", "memberLayout": "separatePages" } diff --git a/tools/DocfxImage.psm1 b/tools/DocfxImage.psm1 new file mode 100644 index 0000000..1b5ec2a --- /dev/null +++ b/tools/DocfxImage.psm1 @@ -0,0 +1,582 @@ +#requires -Version 7.0 +Set-StrictMode -Version Latest + +$script:RepoRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path +$script:SemVerPattern = '^(?0|[1-9][0-9]*)\.(?0|[1-9][0-9]*)\.(?0|[1-9][0-9]*)(?:-(?(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?$' +$script:ReleaseTagPattern = '^v(?(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*))$' +$script:DockerTagPattern = '^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$' +$script:EngineSuffixPattern = '-v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?$' +$script:RepositoryPattern = '^(?:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::[0-9]+)?/)?[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*(?:/[a-z0-9]+(?:(?:[._]|__|[-]+)[a-z0-9]+)*)*$' +$script:SkopeoUtilityImage = 'quay.io/skopeo/stable:v1.20.0' +$script:CanonicalSourceRepository = 'https://github.com/codebeltnet/docfx' +$script:RequiredPlatforms = @('linux/arm64', 'linux/amd64') + +function Resolve-SemVer { + param( + [string] $Value, + [Parameter(Mandatory)][string] $Name + ) + + if ([string]::IsNullOrWhiteSpace($Value)) { + throw "$Name must not be empty. Specify a Semantic Version such as '1.1.0'." + } + if ($Value.Contains('+')) { + throw "Invalid $Name '$Value'. Semantic Versioning build metadata ('+...') is not valid in Docker image tags." + } + if ($Value -cmatch '^v\d') { + throw "Invalid $Name '$Value'. Specify a Semantic Version without a leading 'v' (for example, '$($Value.Substring(1))')." + } + if ($Value -cnotmatch $script:SemVerPattern) { + throw "Invalid $Name '$Value'. Specify a valid Semantic Version (MAJOR.MINOR.PATCH with optional -PRERELEASE)." + } + + [pscustomobject]@{ + Value = $Value + Major = $Matches['major'] + Minor = $Matches['minor'] + Patch = $Matches['patch'] + Prerelease = $Matches['prerelease'] + IsPrerelease = [bool]$Matches['prerelease'] + } +} + +function Resolve-ReleaseTagVersion { + param([string] $Tag) + + if ([string]::IsNullOrWhiteSpace($Tag) -or $Tag -cnotmatch $script:ReleaseTagPattern) { + throw "Invalid release tag '$Tag'. Release tags must follow vMAJOR.MINOR.PATCH (for example, 'v1.1.0')." + } + $Matches['version'] +} + +function Get-DocfxDefaultVersion { + param([string] $RootPath = $script:RepoRoot) + + $dockerfilePath = Join-Path $RootPath 'Dockerfile' + if (!(Test-Path -LiteralPath $dockerfilePath -PathType Leaf)) { + throw "Authoritative Dockerfile was not found at '$dockerfilePath'." + } + $dockerfile = Get-Content -LiteralPath $dockerfilePath -Raw + if ($dockerfile -cnotmatch '(?m)^(?:\uFEFF)?ARG DOCFX_VERSION=(?\S+)\r?$') { + throw "Dockerfile does not declare 'ARG DOCFX_VERSION='." + } + (Resolve-SemVer $Matches['version'] 'DocfxVersion').Value +} + +function Test-DocfxVersionConsistency { + param([string] $RootPath = $script:RepoRoot) + + $expected = Get-DocfxDefaultVersion -RootPath $RootPath + $generatorPath = Join-Path $RootPath 'framework-views/Build-DocfxFrameworkViews.ps1' + $compatPath = Join-Path $RootPath 'templates/ms-style/framework-views.compat' + + $generator = Get-Content -LiteralPath $generatorPath -Raw + if ($generator -cnotmatch "(?m)^\`$supportedDocfx = '$([regex]::Escape($expected))'\r?$") { + throw "framework-views/Build-DocfxFrameworkViews.ps1 `$supportedDocfx does not match Dockerfile ARG DOCFX_VERSION ('$expected')." + } + + $compat = (Get-Content -LiteralPath $compatPath -Raw).Trim() + $expectedCompat = "framework-views-v1/docfx-$expected" + if ($compat -cne $expectedCompat) { + throw "templates/ms-style/framework-views.compat ('$compat') does not match expected '$expectedCompat'." + } + + $expected +} + +function Test-IsOfficialDocfxRepository { + param([Parameter(Mandatory)][string] $Repository) + + $Repository -cin @('codebeltnet/docfx', 'docker.io/codebeltnet/docfx') +} + +function Resolve-DocfxImageTagPlan { + param( + [Parameter(Mandatory)][pscustomobject] $CliVersion, + [pscustomobject] $Engine, + [Parameter(Mandatory)][string] $Repository + ) + + if ($Repository -cnotmatch $script:RepositoryPattern) { + throw "Invalid Docker repository '$Repository'. Use lowercase repository segments without tags or whitespace." + } + + $versionedBases = if ($CliVersion.IsPrerelease) { + @($CliVersion.Value) + } else { + @($CliVersion.Value, "$($CliVersion.Major).$($CliVersion.Minor)", $CliVersion.Major) + } + + $convenienceTags = if ($Engine -and $Engine.IsPrerelease) { + @() + } elseif ($CliVersion.IsPrerelease) { + @($CliVersion.Value) + } else { + @($versionedBases + @('latest')) + } + + $engineQualifiedTags = if ($Engine) { + @($versionedBases | ForEach-Object { "$_-v$($Engine.Value)" }) + } else { + @() + } + + foreach ($convenienceTag in $convenienceTags) { + if ($convenienceTag -cmatch $script:EngineSuffixPattern) { + throw "Convenience tag '$convenienceTag' conflicts with the engine-qualified '-v' tag convention." + } + } + + $allTags = @($engineQualifiedTags) + @($convenienceTags) + foreach ($candidate in $allTags) { + if ($candidate.Length -gt 128 -or $candidate -cnotmatch $script:DockerTagPattern) { + throw "Generated Docker tag '$candidate' violates Docker tag constraints (length $($candidate.Length), maximum 128)." + } + } + + [pscustomobject]@{ + Repository = $Repository + ConvenienceTags = $convenienceTags + EngineQualifiedTags = $engineQualifiedTags + AllTags = $allTags + ConvenienceReferences = @($convenienceTags | ForEach-Object { "${Repository}:$_" }) + EngineQualifiedReferences = @($engineQualifiedTags | ForEach-Object { "${Repository}:$_" }) + AllReferences = @($allTags | ForEach-Object { "${Repository}:$_" }) + } +} + +function Get-DocfxOciLabels { + param( + [Parameter(Mandatory)][pscustomobject] $CliVersion, + [pscustomobject] $Engine, + [string] $Revision, + [string] $SourceRepository = $script:CanonicalSourceRepository, + [string] $CreatedUtc = [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ') + ) + + $labels = [ordered]@{ + 'org.opencontainers.image.created' = $CreatedUtc + 'org.opencontainers.image.source' = $SourceRepository + } + if ($Revision) { + $labels['org.opencontainers.image.revision'] = $Revision + } + if ($Engine) { + $labels['org.opencontainers.image.version'] = $Engine.Value + $labels['net.codebelt.docfx.engine.version'] = $Engine.Value + } + $labels['net.codebelt.docfx.cli.version'] = $CliVersion.Value + $labels +} + +function Get-DocfxSourceRevision { + param( + [switch] $Required, + [string] $RootPath = $script:RepoRoot + ) + + $output = & git -C $RootPath rev-parse HEAD 2>&1 + $revision = ((@($output) | ForEach-Object { $_.ToString() }) -join '').Trim() + if ($LASTEXITCODE -eq 0 -and $revision -cmatch '^[0-9a-f]{40}$') { + return $revision + } + if ($Required) { + throw 'A valid Git source revision is required (git rev-parse HEAD failed).' + } +} + +function Invoke-DocfxDocker { + param([Parameter(Mandatory)][string[]] $Arguments) + + & docker @Arguments + if ($LASTEXITCODE -ne 0) { + throw "docker $($Arguments -join ' ') exited with code $LASTEXITCODE." + } +} + +function Assert-NativeDockerHost { + param( + [Parameter(Mandatory)][string] $Platform, + [string] $DockerContext + ) + + $dockerArgs = if ($DockerContext) { + @('--context', $DockerContext, 'info', '--format', '{{.OSType}}/{{.Architecture}}') + } else { + @('info', '--format', '{{.OSType}}/{{.Architecture}}') + } + $daemon = & docker @dockerArgs 2>&1 + if ($LASTEXITCODE -ne 0) { + throw "Cannot access native Docker host for '$Platform'." + } + $normalized = ((@($daemon) | ForEach-Object { $_.ToString() }) -join '').Trim().Replace('x86_64', 'amd64').Replace('aarch64', 'arm64') + if ($normalized -cne $Platform) { + throw "Native Docker host required for '$Platform'; got '$normalized'. Emulation is insufficient for native validation." + } +} + +function Test-SkopeoTransport { + if (Get-Command skopeo -ErrorAction SilentlyContinue) { + return $true + } + + $dockerHost = if (-not $env:DOCKER_CONTEXT) { $env:DOCKER_HOST } else { $null } + if (-not $dockerHost) { + $output = & docker context inspect --format '{{.Endpoints.docker.Host}}' 2>&1 + if ($LASTEXITCODE -ne 0) { + throw 'Unable to inspect active Docker context for Skopeo utility transport.' + } + $dockerHost = ((@($output) | ForEach-Object { $_.ToString() }) -join '').Trim() + } + + if ($dockerHost -notmatch '^(unix|npipe)://') { + throw 'Native Skopeo is required when the active Docker daemon uses SSH or TCP; install skopeo locally or select a local Docker context.' + } + return $false +} + +function Invoke-Skopeo { + param( + [Parameter(Mandatory)][string[]] $Arguments, + [switch] $CaptureOutput + ) + + $useNative = Test-SkopeoTransport + if ($useNative) { + if ($CaptureOutput) { + $stdoutFile = New-TemporaryFile + $stderrFile = New-TemporaryFile + try { + $psi = [System.Diagnostics.ProcessStartInfo]::new((Get-Command skopeo).Source) + $psi.UseShellExecute = $false + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + foreach ($arg in $Arguments) { $psi.ArgumentList.Add($arg) } + $proc = [System.Diagnostics.Process]::Start($psi) + $stderrTask = $proc.StandardError.ReadToEndAsync() + $stdoutStream = [IO.File]::OpenWrite($stdoutFile.FullName) + try { + $proc.StandardOutput.BaseStream.CopyTo($stdoutStream) + } finally { + $stdoutStream.Dispose() + } + $proc.WaitForExit() + $stderrText = $stderrTask.GetAwaiter().GetResult() + if ($proc.ExitCode -ne 0) { + throw "skopeo $($Arguments[0]) exited with code $($proc.ExitCode): $($stderrText.Trim())" + } + return [IO.File]::ReadAllBytes($stdoutFile.FullName) + } finally { + Remove-Item -LiteralPath $stdoutFile.FullName, $stderrFile.FullName -Force -ErrorAction SilentlyContinue + } + } + + & skopeo @Arguments + if ($LASTEXITCODE -ne 0) { + throw "skopeo $($Arguments[0]) exited with code $LASTEXITCODE." + } + return + } + + $dockerArgs = [System.Collections.Generic.List[string]]::new() + $dockerArgs.AddRange([string[]]@('run', '--rm', '--user', '0')) + $converted = [System.Collections.Generic.List[string]]::new() + + for ($i = 0; $i -lt $Arguments.Count; $i++) { + $arg = $Arguments[$i] + if ($arg -match '^(?oci-archive|oci|docker-archive):(?.+)$') { + $transport = $Matches['transport'] + $rest = $Matches['rest'] + $suffix = '' + if ($transport -ceq 'docker-archive' -and $rest -match '^(?.+\.tar):(?.+)$') { + $localPath = $Matches['file'] + $suffix = ':' + $Matches['tag'] + } else { + $localPath = $rest + } + $fullPath = [IO.Path]::GetFullPath($localPath) + $parent = [IO.Path]::GetDirectoryName($fullPath) + $leaf = [IO.Path]::GetFileName($fullPath) + $mount = "/archive$i" + $dockerArgs.AddRange([string[]]@('--volume', "${parent}:${mount}")) + $converted.Add("${transport}:${mount}/${leaf}${suffix}") + } else { + $converted.Add($arg) + } + } + + if ($env:REGISTRY_AUTH_FILE) { + $authPath = [IO.Path]::GetFullPath($env:REGISTRY_AUTH_FILE) + $dockerArgs.AddRange([string[]]@('--volume', "${authPath}:/auth.json:ro", '--env', 'REGISTRY_AUTH_FILE=/auth.json')) + } + $dockerArgs.Add($script:SkopeoUtilityImage) + $dockerArgs.AddRange($converted) + + if ($CaptureOutput) { + $rawText = & docker @($dockerArgs.ToArray()) 2>&1 + if ($LASTEXITCODE -ne 0) { + $errText = ((@($rawText) | ForEach-Object { $_.ToString() }) -join "`n").Trim() + throw "skopeo $($Arguments[0]) exited with code $LASTEXITCODE`: $errText" + } + $joined = (@($rawText) | ForEach-Object { $_.ToString() }) -join "`n" + return [Text.UTF8Encoding]::new($false).GetBytes($joined) + } + + Invoke-DocfxDocker ($dockerArgs.ToArray()) +} + +function Invoke-OciArtifact { + param( + [Parameter(Mandatory)][string[]] $Arguments, + [string] $RootPath = $script:RepoRoot + ) + + $toolPath = Join-Path $RootPath 'tools/OciArtifact.cs' + $output = & dotnet run --file $toolPath -- @Arguments 2>&1 + $lines = @($output | ForEach-Object { $_.ToString() }) + if ($LASTEXITCODE -ne 0) { + throw "OciArtifact $($Arguments[0]) failed (exit $LASTEXITCODE): $($lines -join "`n")" + } + $lines -join "`n" +} + +function Get-RegistryManifestDigest { + param([Parameter(Mandatory)][string] $Reference) + + try { + $raw = Invoke-Skopeo -Arguments @('inspect', '--raw', "docker://$Reference") -CaptureOutput + $hash = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($raw)).ToLowerInvariant() + return "sha256:$hash" + } catch { + $message = $_.Exception.Message + if ($message -match '(?i)\b(?:manifest unknown|name unknown|MANIFEST_UNKNOWN|NAME_UNKNOWN)\b') { + return $null + } + throw "Could not inspect registry reference '$Reference': $message" + } +} + +function Assert-EngineTagAvailableForBuild { + param([Parameter(Mandatory)][string] $Reference) + + $output = & docker buildx imagetools inspect --format '{{json .Manifest}}' $Reference 2>&1 + $exitCode = $LASTEXITCODE + $text = (@($output) | ForEach-Object { $_.ToString() }) -join "`n" + if ($exitCode -eq 0) { + $detail = if ($text -cmatch '"digest"\s*:\s*"(sha256:[0-9a-f]{64})"') { " ($($Matches[1]))" } else { '' } + throw "Published engine-qualified tag '$Reference' already exists in the registry$detail. Refusing to reassign an existing release tag; increment -EngineVersion for a new release." + } + if ($text -notmatch '(?i)(?:not found|manifest unknown|name unknown|MANIFEST_UNKNOWN|NAME_UNKNOWN)') { + throw "Could not verify whether engine-qualified tag '$Reference' exists in the registry (docker exit code $exitCode): $text" + } +} + +function Test-DocfxPromotionPreflight { + param( + [Parameter(Mandatory)][string] $ArchivePath, + [Parameter(Mandatory)][string] $EngineVersion, + [Parameter(Mandatory)][string] $DocfxVersion, + [Parameter(Mandatory)][string] $Revision, + [Parameter(Mandatory)][AllowEmptyCollection()][string[]] $Tags, + [Parameter(Mandatory)][AllowEmptyCollection()][string[]] $EngineQualifiedTags, + [string] $SourceRepository = $script:CanonicalSourceRepository, + [string] $ExpectedIndexDigest, + [string] $Platform, + [switch] $RequireEngineTagsPresent + ) + + $null = Resolve-SemVer $EngineVersion 'EngineVersion' + $null = Resolve-SemVer $DocfxVersion 'DocfxVersion' + + if ($Tags.Count -eq 0) { + throw 'Promotion requires at least one destination tag.' + } + if ($EngineQualifiedTags.Count -eq 0) { + throw 'Promotion requires explicit engine-qualified destination tags.' + } + if (@($Tags | Select-Object -Unique).Count -ne $Tags.Count -or @($EngineQualifiedTags | Select-Object -Unique).Count -ne $EngineQualifiedTags.Count) { + throw 'Promotion destination tags must be unique.' + } + + $repos = @($Tags | ForEach-Object { ($_ -split ':', 2)[0] } | Select-Object -Unique) + if ($repos.Count -ne 1) { + throw 'All promotion destination tags must target one repository.' + } + + foreach ($engineTag in $EngineQualifiedTags) { + if ($engineTag -cnotin $Tags) { + throw "Engine-qualified tag '$engineTag' must be included in destination tags." + } + if (-not $engineTag.EndsWith("-v$EngineVersion", [StringComparison]::Ordinal)) { + throw "Engine-qualified tag '$engineTag' does not match engine version '$EngineVersion'." + } + } + + $null = Invoke-OciArtifact -Arguments @('check-seal', $ArchivePath) + $verifyArgs = @('verify', $ArchivePath, '--version', $EngineVersion, '--docfx-version', $DocfxVersion, '--revision', $Revision, '--source', $SourceRepository, '--no-seal') + if ($Platform) { $verifyArgs += @('--platform', $Platform) } + if ($ExpectedIndexDigest) { $verifyArgs += @('--expected-digest', $ExpectedIndexDigest) } + $verified = Invoke-OciArtifact -Arguments $verifyArgs | ConvertFrom-Json + $digest = $verified.indexDigest + + foreach ($tag in $EngineQualifiedTags) { + $existing = Get-RegistryManifestDigest -Reference $tag + if ($null -eq $existing) { + if ($RequireEngineTagsPresent) { + throw "Required engine-qualified tag '$tag' is absent in the registry before convenience tag promotion." + } + } elseif ($existing -cne $digest) { + throw "Engine-qualified tag conflict for '$tag': expected '$digest', found '$existing'. Refusing to overwrite an existing release." + } + } + + [pscustomobject]@{ + IndexDigest = $digest + Platforms = @($verified.platforms) + Configs = $verified.configs + Repository = $repos[0] + } +} + +function Publish-DocfxOciArchive { + param( + [Parameter(Mandatory)][string] $ArchivePath, + [Parameter(Mandatory)][string] $EngineVersion, + [Parameter(Mandatory)][string] $DocfxVersion, + [Parameter(Mandatory)][string] $Revision, + [Parameter(Mandatory)][string[]] $Tags, + [Parameter(Mandatory)][string[]] $EngineQualifiedTags, + [string] $SourceRepository = $script:CanonicalSourceRepository, + [string] $ExpectedIndexDigest, + [string] $Platform, + [scriptblock] $BeforeConvenience + ) + + $preflight = Test-DocfxPromotionPreflight ` + -ArchivePath $ArchivePath ` + -EngineVersion $EngineVersion ` + -DocfxVersion $DocfxVersion ` + -Revision $Revision ` + -Tags $Tags ` + -EngineQualifiedTags $EngineQualifiedTags ` + -SourceRepository $SourceRepository ` + -ExpectedIndexDigest $ExpectedIndexDigest ` + -Platform $Platform + + $expectedDigest = $preflight.IndexDigest + $convenienceTags = @($Tags | Where-Object { $_ -cnotin $EngineQualifiedTags }) + $layoutDir = Join-Path ([IO.Path]::GetTempPath()) ('docfx-oci-layout-' + [guid]::NewGuid().ToString('N')) + $published = [System.Collections.Generic.List[object]]::new() + + try { + $null = Invoke-OciArtifact -Arguments @('extract-layout', $ArchivePath, '--output-dir', $layoutDir) + + foreach ($tag in $EngineQualifiedTags) { + $existing = Get-RegistryManifestDigest -Reference $tag + if ($null -ne $existing -and $existing -cne $expectedDigest) { + throw "Engine-qualified tag conflict for '$tag': expected '$expectedDigest', found '$existing'. Refusing to overwrite." + } + if ($null -eq $existing) { + Invoke-Skopeo -Arguments @('copy', '--all', '--preserve-digests', "oci:$layoutDir", "docker://$tag") + } + + $raw = Invoke-Skopeo -Arguments @('inspect', '--raw', "docker://$tag") -CaptureOutput + $actualDigest = 'sha256:' + [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($raw)).ToLowerInvariant() + if ($actualDigest -cne $expectedDigest) { + throw "Registry OCI index digest changed for '$tag': expected '$expectedDigest', found '$actualDigest'." + } + $published.Add([pscustomobject]@{ tag = $tag; digest = $actualDigest; family = 'engine-qualified' }) + } + + if ($convenienceTags.Count -gt 0) { + if ($BeforeConvenience) { + & $BeforeConvenience + } + + $null = Test-DocfxPromotionPreflight ` + -ArchivePath $ArchivePath ` + -EngineVersion $EngineVersion ` + -DocfxVersion $DocfxVersion ` + -Revision $Revision ` + -Tags $Tags ` + -EngineQualifiedTags $EngineQualifiedTags ` + -SourceRepository $SourceRepository ` + -ExpectedIndexDigest $expectedDigest ` + -Platform $Platform ` + -RequireEngineTagsPresent + + foreach ($tag in $convenienceTags) { + Invoke-Skopeo -Arguments @('copy', '--all', '--preserve-digests', "oci:$layoutDir", "docker://$tag") + $raw = Invoke-Skopeo -Arguments @('inspect', '--raw', "docker://$tag") -CaptureOutput + $actualDigest = 'sha256:' + [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($raw)).ToLowerInvariant() + if ($actualDigest -cne $expectedDigest) { + throw "Registry OCI index digest changed for '$tag': expected '$expectedDigest', found '$actualDigest'." + } + $published.Add([pscustomobject]@{ tag = $tag; digest = $actualDigest; family = 'convenience' }) + } + } + + # Download promoted content once by immutable digest and re-verify full OCI archive integrity. + $verifyDir = Join-Path ([IO.Path]::GetTempPath()) ('docfx-registry-verify-' + [guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $verifyDir -Force | Out-Null + try { + $downloaded = Join-Path $verifyDir 'registry.oci.tar' + Invoke-Skopeo -Arguments @('copy', '--all', '--preserve-digests', "docker://$($preflight.Repository)@$expectedDigest", "oci-archive:$downloaded") + $verifyArgs = @('verify', $downloaded, '--version', $EngineVersion, '--docfx-version', $DocfxVersion, '--revision', $Revision, '--source', $SourceRepository, '--expected-digest', $expectedDigest, '--no-seal') + if ($Platform) { $verifyArgs += @('--platform', $Platform) } + $null = Invoke-OciArtifact -Arguments $verifyArgs + } finally { + if (Test-Path -LiteralPath $verifyDir) { + Remove-Item -LiteralPath $verifyDir -Recurse -Force + } + } + } finally { + if (Test-Path -LiteralPath $layoutDir) { + Remove-Item -LiteralPath $layoutDir -Recurse -Force + } + } + + $records = $published.ToArray() + ConvertTo-Json -InputObject $records -Depth 5 | Set-Content -LiteralPath "$ArchivePath.published.json" -Encoding utf8NoBOM + + if ($env:GITHUB_STEP_SUMMARY) { + $summaryLines = @( + '### Promoted DocFX Docker Hub Images' + '' + "- DocFX CLI: $DocfxVersion" + "- Codebelt engine: $EngineVersion" + "- Source revision: $Revision" + "- Verified OCI index digest: ``$expectedDigest``" + "- Engine-qualified tags: $($EngineQualifiedTags -join ', ')" + "- Convenience tags: $($convenienceTags -join ', ')" + '' + ) + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value ($summaryLines -join "`n") -Encoding utf8NoBOM + } + + [pscustomobject]@{ + IndexDigest = $expectedDigest + Repository = $preflight.Repository + Published = $records + } +} + +Export-ModuleMember -Function @( + 'Resolve-SemVer' + 'Resolve-ReleaseTagVersion' + 'Get-DocfxDefaultVersion' + 'Test-DocfxVersionConsistency' + 'Test-IsOfficialDocfxRepository' + 'Resolve-DocfxImageTagPlan' + 'Get-DocfxOciLabels' + 'Get-DocfxSourceRevision' + 'Invoke-DocfxDocker' + 'Assert-NativeDockerHost' + 'Test-SkopeoTransport' + 'Invoke-Skopeo' + 'Invoke-OciArtifact' + 'Get-RegistryManifestDigest' + 'Assert-EngineTagAvailableForBuild' + 'Test-DocfxPromotionPreflight' + 'Publish-DocfxOciArchive' +) diff --git a/tools/Invoke-DocfxRelease.ps1 b/tools/Invoke-DocfxRelease.ps1 new file mode 100644 index 0000000..7805a9b --- /dev/null +++ b/tools/Invoke-DocfxRelease.ps1 @@ -0,0 +1,504 @@ +#requires -Version 7.0 +[CmdletBinding()] +param( + [Parameter(Mandatory)] + [ValidateSet('ValidateTag', 'Assemble', 'Split', 'VerifyDraftAssets', 'Resolve', 'Restore', 'Publish')] + [string] $Command, + [string] $InputsDir = 'inputs', + [string] $OutDir = 'out', + [string] $AssetsDir = 'assets', + [string] $ResolvedDir = 'resolved', + [string] $ReleaseDir = 'release', + [long] $PartSizeBytes = 1073741824 +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $false + +$repoRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path +Import-Module (Join-Path $PSScriptRoot 'DocfxImage.psm1') + +function Invoke-GitHubApi { + param([Parameter(Mandatory)][string] $Endpoint) + + $raw = & gh api $Endpoint 2>&1 + if ($LASTEXITCODE -ne 0) { + $text = (@($raw) | ForEach-Object { $_.ToString() }) -join "`n" + throw "gh api $Endpoint exited with code $LASTEXITCODE`: $text" + } + ((@($raw) | ForEach-Object { $_.ToString() }) -join "`n") | ConvertFrom-Json -AsHashtable +} + +function Invoke-ReleaseAssetDownload { + param( + [Parameter(Mandatory)][hashtable] $Asset, + [Parameter(Mandatory)][string] $Destination + ) + + if (-not $Asset['digest'] -or $Asset['digest'] -cnotmatch '^sha256:[0-9a-f]{64}$') { + throw "Release asset '$($Asset['name'])' has no authoritative SHA-256 digest." + } + if (-not $Asset['browser_download_url']) { + throw "Release asset '$($Asset['name'])' has no download URL." + } + + Invoke-WebRequest -Uri $Asset['browser_download_url'] -OutFile $Destination + $actualHash = (Get-FileHash -LiteralPath $Destination -Algorithm SHA256).Hash.ToLowerInvariant() + $actualSize = (Get-Item -LiteralPath $Destination).Length + if ("sha256:$actualHash" -cne $Asset['digest'] -or $actualSize -ne [long]$Asset['size']) { + throw "Release asset '$($Asset['name'])' checksum or size mismatch." + } +} + +function Assert-TagPlanMatchesAuthoritativeScript { + param([Parameter(Mandatory)][hashtable] $Meta) + + $plan = & (Join-Path $repoRoot 'BuildAndPushDocfxImage.ps1') ` + -DocfxVersion $Meta['DocfxVersion'] ` + -EngineVersion $Meta['EngineVersion'] ` + -ContainerRegistry 'codebeltnet/' ` + -Tag 'docfx' ` + -BuildOnly ` + -Platform 'linux/amd64' ` + -WhatIf ` + -PassThru + + foreach ($key in @('Tags', 'ConvenienceTags', 'EngineQualifiedTags')) { + $expected = @($plan.$key) + $actual = @($Meta[$key]) + if (($expected -join ',') -cne ($actual -join ',')) { + throw "Saved release metadata '$key' differs from authoritative BuildAndPushDocfxImage tag contract." + } + } +} + +function Write-ReleaseSummary { + param([Parameter(Mandatory)][hashtable] $Meta) + + if (-not $env:GITHUB_STEP_SUMMARY) { return } + $lines = [System.Collections.Generic.List[string]]::new() + $lines.Add("### DocFX Release $($Meta['ReleaseTag'])") + $lines.Add('') + $lines.Add("- DocFX CLI: $($Meta['DocfxVersion'])") + $lines.Add("- Codebelt engine: $($Meta['EngineVersion'])") + $lines.Add("- Source revision: $($Meta['SourceCommit'])") + $lines.Add("- Verified OCI index: ``$($Meta['OciIndexDigest'])``") + $lines.Add("- Engine-qualified tags: $(@($Meta['EngineQualifiedTags']) -join ', ')") + $lines.Add("- Convenience tags: $(@($Meta['ConvenienceTags']) -join ', ')") + foreach ($record in @($Meta['Verification'])) { + $lines.Add("- $($record['Platform']): native validation passed; image size $($record['SizeBytes']) bytes; OCI archive $($record['OciArchiveBytes']) bytes") + } + $lines.Add('') + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value ($lines -join "`n") -Encoding utf8NoBOM +} + +function Assert-CurrentLatestRelease { + $identityPath = Join-Path $ResolvedDir 'identity.json' + if (!(Test-Path -LiteralPath $identityPath -PathType Leaf)) { + throw "Resolved release identity file is missing at '$identityPath'." + } + $resolved = Get-Content -LiteralPath $identityPath -Raw | ConvertFrom-Json -AsHashtable + $repo = $env:GITHUB_REPOSITORY + $latest = Invoke-GitHubApi -Endpoint "repos/$repo/releases/latest" + if ($latest['id'] -ne $resolved['releaseId'] -or $latest['tag_name'] -cne $resolved['tag'] -or $latest['draft'] -or $latest['prerelease']) { + throw "Latest published release changed after verification (resolved $($resolved['tag']), latest $($latest['tag_name'])); refusing stale convenience tag promotion." + } + $resolved +} + +function Invoke-ValidateTag { + $tag = $env:GITHUB_REF_NAME + $engineVersion = Resolve-ReleaseTagVersion -Tag $tag + $docfxVersion = Test-DocfxVersionConsistency -RootPath $repoRoot + $headSha = Get-DocfxSourceRevision -Required -RootPath $repoRoot + if ($env:GITHUB_SHA -and $headSha -cne $env:GITHUB_SHA) { + throw "Checked-out revision '$headSha' does not match GITHUB_SHA '$($env:GITHUB_SHA)'." + } + + if ($env:GITHUB_OUTPUT) { + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "engine-version=$engineVersion" -Encoding utf8NoBOM + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "docfx-version=$docfxVersion" -Encoding utf8NoBOM + } + + Write-Output "Validated release tag $tag (engine $engineVersion, DocFX CLI $docfxVersion, revision $headSha)." +} + +function Invoke-Assemble { + $expectedTag = $env:GITHUB_REF_NAME + $expectedEngineVersion = Resolve-ReleaseTagVersion -Tag $expectedTag + $expectedSha = $env:GITHUB_SHA + $expectedDocfxVersion = Test-DocfxVersionConsistency -RootPath $repoRoot + + $metaFiles = @(Get-ChildItem -LiteralPath $InputsDir -Filter 'docfx-image.json' -Recurse -File | Sort-Object FullName) + if ($metaFiles.Count -ne 2) { + throw "Both native verification records (amd64 and arm64) are required; found $($metaFiles.Count)." + } + + $records = @(foreach ($file in $metaFiles) { + Get-Content -LiteralPath $file.FullName -Raw | ConvertFrom-Json -AsHashtable + }) + + $first = $records[0] + foreach ($record in $records) { + if ($record['NativeVerified'] -ne $true) { + throw "Native verification record for '$($record['Platform'])' is not verified." + } + foreach ($key in @('DocfxVersion', 'EngineVersion', 'SourceCommit', 'SourceRepository')) { + if ($record[$key] -cne $first[$key]) { + throw "Native verification identity mismatch on '$key'." + } + } + foreach ($listKey in @('Tags', 'ConvenienceTags', 'EngineQualifiedTags')) { + if ((@($record[$listKey]) -join ',') -cne (@($first[$listKey]) -join ',')) { + throw "Native verification tag mismatch on '$listKey'." + } + } + } + + $platforms = @($records | ForEach-Object { $_['Platform'] } | Sort-Object) + if (($platforms -join ',') -cne 'linux/amd64,linux/arm64') { + throw "Both native CPUs (linux/amd64 and linux/arm64) are required; found '$($platforms -join ',')'." + } + if ($first['SourceCommit'] -cne $expectedSha -or $first['EngineVersion'] -cne $expectedEngineVersion -or $first['DocfxVersion'] -cne $expectedDocfxVersion) { + throw 'Release source, engine version, or DocFX CLI version does not match native verification records.' + } + + Assert-TagPlanMatchesAuthoritativeScript -Meta $first + + $archiveFiles = @(Get-ChildItem -LiteralPath $InputsDir -Filter '*.oci.tar' -Recurse -File | Sort-Object FullName) + if ($archiveFiles.Count -ne 2) { + throw "Exactly two native OCI archives are required; found $($archiveFiles.Count)." + } + + $verifiedInputs = [System.Collections.Generic.List[string]]::new() + foreach ($archiveFile in $archiveFiles) { + $parentMetaFile = Join-Path $archiveFile.DirectoryName 'docfx-image.json' + $record = Get-Content -LiteralPath $parentMetaFile -Raw | ConvertFrom-Json -AsHashtable + $cpu = $record['Architecture'] + $verified = Invoke-OciArtifact -Arguments @( + 'verify', $archiveFile.FullName + '--version', $expectedEngineVersion + '--docfx-version', $expectedDocfxVersion + '--revision', $expectedSha + '--source', $first['SourceRepository'] + '--platform', $cpu + '--check-seal' + '--no-seal' + ) -RootPath $repoRoot | ConvertFrom-Json + if ($verified.configs.$cpu -cne $record['ConfigDigest']) { + throw "Native test record for '$cpu' does not match the assembled OCI image config digest." + } + if ($verified.archiveSha256 -cne $record['ArchiveSha256']) { + throw "Native test record for '$cpu' does not match the OCI archive SHA-256." + } + if ($archiveFile.Length -ne $record['OciArchiveBytes']) { + throw "Native test record for '$cpu' does not match the OCI archive size." + } + $verifiedInputs.Add($archiveFile.FullName) + } + + New-Item -ItemType Directory -Path $OutDir -Force | Out-Null + $combinedArchive = Join-Path (Resolve-Path -LiteralPath $OutDir).Path 'docfx.oci.tar' + $mergeArgs = @( + 'merge', $combinedArchive + '--version', $expectedEngineVersion + '--docfx-version', $expectedDocfxVersion + '--revision', $expectedSha + '--source', $first['SourceRepository'] + ) + foreach ($inputPath in $verifiedInputs) { + $mergeArgs += @('--input', $inputPath) + } + $merged = Invoke-OciArtifact -Arguments $mergeArgs -RootPath $repoRoot | ConvertFrom-Json + + $releaseMeta = [ordered]@{ + ReleaseTag = $expectedTag + DocfxVersion = $expectedDocfxVersion + EngineVersion = $expectedEngineVersion + SourceCommit = $expectedSha + SourceRepository = $first['SourceRepository'] + Repository = $first['Repository'] + Tags = @($first['Tags']) + ConvenienceTags = @($first['ConvenienceTags']) + EngineQualifiedTags = @($first['EngineQualifiedTags']) + OciIndexDigest = $merged.indexDigest + ArchiveSha256 = $merged.archiveSha256 + ArchiveBytes = $merged.archiveBytes + ReleaseRunId = $env:GITHUB_RUN_ID + ReleaseRunAttempt = $env:GITHUB_RUN_ATTEMPT + Verification = $records + } + $releaseMeta | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath (Join-Path $OutDir 'release.json') -Encoding utf8NoBOM + Write-ReleaseSummary -Meta $releaseMeta + + if ($env:GITHUB_OUTPUT) { + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "digest=$($merged.indexDigest)" -Encoding utf8NoBOM + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "version=$expectedEngineVersion" -Encoding utf8NoBOM + } + Write-Output "Assembled multi-platform OCI index $($merged.indexDigest)." +} + +function Invoke-Split { + $archivePath = Join-Path $OutDir 'docfx.oci.tar' + $releaseJsonPath = Join-Path $OutDir 'release.json' + if (!(Test-Path -LiteralPath $archivePath -PathType Leaf) -or !(Test-Path -LiteralPath $releaseJsonPath -PathType Leaf)) { + throw "Expected assembled archive and release.json in '$OutDir'." + } + + New-Item -ItemType Directory -Path $AssetsDir -Force | Out-Null + $splitResult = Invoke-OciArtifact -Arguments @( + 'split', $archivePath + '--output-dir', $AssetsDir + '--prefix', 'docfx' + '--part-size', "$PartSizeBytes" + '--write-checksum' + ) -RootPath $repoRoot | ConvertFrom-Json + + $meta = Get-Content -LiteralPath $releaseJsonPath -Raw | ConvertFrom-Json -AsHashtable + $meta['ArchiveSha256'] = $splitResult.archiveSha256 + $meta['ArchiveBytes'] = $splitResult.archiveBytes + $meta['Pieces'] = @(foreach ($piece in $splitResult.pieces) { + [ordered]@{ + Name = $piece.name + Sha256 = $piece.sha256 + Size = $piece.size + } + }) + $meta | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath (Join-Path $AssetsDir 'docfx-release.json') -Encoding utf8NoBOM + Write-Output "Prepared $($meta['Pieces'].Count) release asset piece(s) in '$AssetsDir'." +} + +function Invoke-VerifyDraftAssets { + $repo = $env:GITHUB_REPOSITORY + $tag = $env:RELEASE_TAG + $null = Resolve-ReleaseTagVersion -Tag $tag + + $localFiles = @(Get-ChildItem -LiteralPath $ReleaseDir -File | Sort-Object Name) + if ($localFiles.Count -eq 0) { + throw "No release asset files found in '$ReleaseDir'." + } + + $releases = @(Invoke-GitHubApi -Endpoint "repos/$repo/releases?per_page=30") + $draft = @($releases | Where-Object { $_['tag_name'] -ceq $tag -and $_['draft'] -eq $true }) + if ($draft.Count -ne 1) { + throw "Expected exactly one draft GitHub release for tag '$tag'; found $($draft.Count)." + } + + $attached = @{} + foreach ($asset in @($draft[0]['assets'])) { + $attached[$asset['name']] = $asset + } + + foreach ($file in $localFiles) { + if (-not $attached.ContainsKey($file.Name)) { + throw "Draft release '$tag' is missing expected asset '$($file.Name)'." + } + $remote = $attached[$file.Name] + if ([long]$remote['size'] -ne $file.Length) { + throw "Draft release asset '$($file.Name)' size mismatch: expected $($file.Length), found $($remote['size'])." + } + if ($remote['digest']) { + $localDigest = 'sha256:' + (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant() + if ($remote['digest'] -cne $localDigest) { + throw "Draft release asset '$($file.Name)' digest mismatch: expected $localDigest, found $($remote['digest'])." + } + } + } + + Write-Output "Verified $($localFiles.Count) durable asset(s) attached to draft release $tag." +} + +function Invoke-Resolve { + $repo = $env:GITHUB_REPOSITORY + if ($repo -cne 'codebeltnet/docfx') { + throw "Production deployment is restricted to 'codebeltnet/docfx'; got '$repo'." + } + + $tag = $env:RELEASE_TAG + $engineVersion = Resolve-ReleaseTagVersion -Tag $tag + $eventName = $env:GITHUB_EVENT_NAME + + $eventData = $null + if ($eventName -ceq 'workflow_dispatch') { + if ($env:GITHUB_REF -cne 'refs/heads/main') { + throw "Deployment recovery must be dispatched from 'refs/heads/main'; got '$($env:GITHUB_REF)'." + } + } else { + $eventData = Get-Content -LiteralPath $env:GITHUB_EVENT_PATH -Raw | ConvertFrom-Json -AsHashtable + if ($eventName -cne 'release' -or $eventData['action'] -cne 'published' -or $eventData['release']['tag_name'] -cne $tag) { + throw 'Unexpected release event payload for production deployment.' + } + } + + $release = Invoke-GitHubApi -Endpoint "repos/$repo/releases/tags/$tag" + $latest = Invoke-GitHubApi -Endpoint "repos/$repo/releases/latest" + if ($release['draft'] -or $release['prerelease'] -or -not $release['published_at'] -or $latest['id'] -ne $release['id']) { + throw "Requested release '$tag' must be the latest published stable release. Refusing to deploy drafts, prereleases, or superseded releases." + } + if ($eventName -ceq 'release' -and $eventData['release']['id'] -ne $release['id']) { + throw 'Published release ID changed during resolution.' + } + + $commit = (Invoke-GitHubApi -Endpoint "repos/$repo/commits/$tag")['sha'] + if ($commit -cnotmatch '^[0-9a-f]{40}$') { + throw "Unable to resolve commit SHA for release tag '$tag'." + } + $comparison = Invoke-GitHubApi -Endpoint "repos/$repo/compare/$commit...main" + if ($comparison['status'] -cnotin @('ahead', 'identical')) { + throw "Release source commit '$commit' is not in main branch history (status '$($comparison['status'])')." + } + + $assets = @{} + foreach ($asset in @($release['assets'])) { + $assets[$asset['name']] = $asset + } + foreach ($requiredAsset in @('docfx-release.json', 'docfx.oci.tar.sha256')) { + if (-not $assets.ContainsKey($requiredAsset)) { + throw "Published release '$tag' is missing required durable asset '$requiredAsset'." + } + } + + New-Item -ItemType Directory -Path $ResolvedDir -Force | Out-Null + $identity = [ordered]@{ + tag = $tag + engineVersion = $engineVersion + releaseId = $release['id'] + sha = $commit + assets = $assets + } + $identity | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath (Join-Path $ResolvedDir 'identity.json') -Encoding utf8NoBOM + + if ($env:GITHUB_OUTPUT) { + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "sha=$commit" -Encoding utf8NoBOM + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "engine-version=$engineVersion" -Encoding utf8NoBOM + } + Write-Output "Resolved latest published release $tag at $commit." +} + +function Invoke-Restore { + $identityPath = Join-Path $ResolvedDir 'identity.json' + if (!(Test-Path -LiteralPath $identityPath -PathType Leaf)) { + throw "Resolved release identity file is missing at '$identityPath'." + } + $resolved = Get-Content -LiteralPath $identityPath -Raw | ConvertFrom-Json -AsHashtable + $assets = $resolved['assets'] + + New-Item -ItemType Directory -Path $OutDir -Force | Out-Null + $releaseJsonPath = Join-Path $OutDir 'release.json' + $checksumAssetPath = Join-Path $OutDir 'docfx.oci.tar.sha256.asset' + Invoke-ReleaseAssetDownload -Asset $assets['docfx-release.json'] -Destination $releaseJsonPath + Invoke-ReleaseAssetDownload -Asset $assets['docfx.oci.tar.sha256'] -Destination $checksumAssetPath + + $meta = Get-Content -LiteralPath $releaseJsonPath -Raw | ConvertFrom-Json -AsHashtable + if ($meta['ReleaseTag'] -cne $resolved['tag'] -or + $meta['EngineVersion'] -cne $resolved['engineVersion'] -or + $meta['SourceCommit'] -cne $resolved['sha']) { + throw 'Release metadata does not match the resolved published release identity.' + } + + $repo = $env:GITHUB_REPOSITORY + $run = Invoke-GitHubApi -Endpoint "repos/$repo/actions/runs/$($meta['ReleaseRunId'])/attempts/$($meta['ReleaseRunAttempt'])" + if ($run['event'] -cne 'push' -or + $run['path'] -cne '.github/workflows/release.yml' -or + $run['head_sha'] -cne $resolved['sha'] -or + $run['head_branch'] -cne $resolved['tag'] -or + [int]$run['run_attempt'] -ne [int]$meta['ReleaseRunAttempt'] -or + $run['conclusion'] -cne 'success') { + throw 'Authoritative tag release workflow run did not succeed for this release and commit.' + } + + $records = @($meta['Verification']) + $recordPlatforms = @($records | ForEach-Object { $_['Platform'] } | Sort-Object) + if ($records.Count -ne 2 -or ($recordPlatforms -join ',') -cne 'linux/amd64,linux/arm64') { + throw 'Both native architecture verification records (linux/amd64 and linux/arm64) are required.' + } + foreach ($record in $records) { + if ($record['NativeVerified'] -ne $true -or + $record['DocfxVersion'] -cne $meta['DocfxVersion'] -or + $record['EngineVersion'] -cne $meta['EngineVersion'] -or + $record['SourceCommit'] -cne $meta['SourceCommit'] -or + (@($record['Tags']) -join ',') -cne (@($meta['Tags']) -join ',') -or + (@($record['ConvenienceTags']) -join ',') -cne (@($meta['ConvenienceTags']) -join ',') -or + (@($record['EngineQualifiedTags']) -join ',') -cne (@($meta['EngineQualifiedTags']) -join ',')) { + throw 'Native verification record identity mismatch.' + } + } + + Assert-TagPlanMatchesAuthoritativeScript -Meta $meta + + $piecesDir = Join-Path $OutDir 'pieces' + New-Item -ItemType Directory -Path $piecesDir -Force | Out-Null + try { + foreach ($piece in @($meta['Pieces'])) { + $pieceName = $piece['Name'] + if ($pieceName -cnotmatch '^docfx\.oci\.part\d{3}$') { + throw "Invalid release archive piece name '$pieceName'." + } + if (-not $assets.ContainsKey($pieceName)) { + throw "Published release is missing archive piece '$pieceName'." + } + $piecePath = Join-Path $piecesDir $pieceName + Invoke-ReleaseAssetDownload -Asset $assets[$pieceName] -Destination $piecePath + } + + $archivePath = Join-Path (Resolve-Path -LiteralPath $OutDir).Path 'docfx.oci.tar' + $null = Invoke-OciArtifact -Arguments @( + 'reassemble' + '--manifest', $releaseJsonPath + '--input-dir', $piecesDir + '--output', $archivePath + '--checksum', $checksumAssetPath + ) -RootPath $repoRoot + + $null = Invoke-OciArtifact -Arguments @( + 'verify', $archivePath + '--version', $meta['EngineVersion'] + '--docfx-version', $meta['DocfxVersion'] + '--revision', $meta['SourceCommit'] + '--source', $meta['SourceRepository'] + '--expected-digest', $meta['OciIndexDigest'] + '--check-seal' + '--no-seal' + ) -RootPath $repoRoot + } finally { + if (Test-Path -LiteralPath $piecesDir) { + Remove-Item -LiteralPath $piecesDir -Recurse -Force + } + if (Test-Path -LiteralPath $checksumAssetPath) { + Remove-Item -LiteralPath $checksumAssetPath -Force + } + } + + Write-ReleaseSummary -Meta $meta + $meta +} + +function Invoke-Publish { + $null = Assert-CurrentLatestRelease + $meta = Invoke-Restore + $archivePath = Join-Path (Resolve-Path -LiteralPath $OutDir).Path 'docfx.oci.tar' + + $result = Publish-DocfxOciArchive ` + -ArchivePath $archivePath ` + -EngineVersion $meta['EngineVersion'] ` + -DocfxVersion $meta['DocfxVersion'] ` + -Revision $meta['SourceCommit'] ` + -SourceRepository $meta['SourceRepository'] ` + -Tags @($meta['Tags']) ` + -EngineQualifiedTags @($meta['EngineQualifiedTags']) ` + -ExpectedIndexDigest $meta['OciIndexDigest'] ` + -BeforeConvenience { $null = Assert-CurrentLatestRelease } + + Write-Output "Promoted $($result.Published.Count) tags to $($result.Repository)@$($result.IndexDigest)." +} + +switch ($Command) { + 'ValidateTag' { Invoke-ValidateTag } + 'Assemble' { Invoke-Assemble } + 'Split' { Invoke-Split } + 'VerifyDraftAssets' { Invoke-VerifyDraftAssets } + 'Resolve' { Invoke-Resolve } + 'Restore' { $null = Invoke-Restore } + 'Publish' { Invoke-Publish } +} diff --git a/tools/Invoke-UnitTests.ps1 b/tools/Invoke-UnitTests.ps1 new file mode 100644 index 0000000..f41ce31 --- /dev/null +++ b/tools/Invoke-UnitTests.ps1 @@ -0,0 +1,70 @@ +#requires -Version 7.0 +[CmdletBinding()] +param( + [string] $CoverageOutputDir = (Join-Path ([IO.Path]::GetTempPath()) 'docfx-coverage'), + [switch] $SkipOciTests +) + +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $false + +$repoRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path +Import-Module Pester -MinimumVersion 5.0.0 -MaximumVersion 5.99.99 -ErrorAction Stop +New-Item -ItemType Directory -Path $CoverageOutputDir -Force | Out-Null + +$suites = @( + @{ + Name = 'framework-views' + Tests = @(Get-ChildItem -LiteralPath (Join-Path $repoRoot 'tests/framework-view') -Filter '*.Tests.ps1' -File | Sort-Object FullName | Select-Object -ExpandProperty FullName) + Coverage = @(Get-ChildItem -LiteralPath (Join-Path $repoRoot 'framework-views') -Filter '*.ps1' -File | Sort-Object FullName | Select-Object -ExpandProperty FullName) + OutputFile = Join-Path $CoverageOutputDir 'docfx-framework-views-coverage.xml' + } + @{ + Name = 'delivery-tooling' + Tests = @( + (Join-Path $repoRoot 'tests/BuildAndPushDocfxImage.Tests.ps1') + (Join-Path $repoRoot 'tests/ReleaseDelivery.Tests.ps1') + ) + Coverage = @( + (Join-Path $repoRoot 'BuildAndPushDocfxImage.ps1') + (Join-Path $repoRoot 'tools/DocfxImage.psm1') + (Join-Path $repoRoot 'tools/Invoke-DocfxRelease.ps1') + ) + OutputFile = Join-Path $CoverageOutputDir 'docfx-delivery-coverage.xml' + } +) + +foreach ($suite in $suites) { + Write-Host "=== Running Pester suite: $($suite.Name) (target coverage: 100%) ===" + $configuration = New-PesterConfiguration + $configuration.Run.Path = $suite.Tests + $configuration.Run.PassThru = $true + $configuration.Output.Verbosity = 'Normal' + $configuration.CodeCoverage.Enabled = $true + $configuration.CodeCoverage.Path = $suite.Coverage + $configuration.CodeCoverage.OutputPath = $suite.OutputFile + $configuration.CodeCoverage.CoveragePercentTarget = 100 + + $result = Invoke-Pester -Configuration $configuration + if ($result.FailedCount -gt 0) { + throw "Pester suite '$($suite.Name)' failed with $($result.FailedCount) failing test(s)." + } + $coveragePercent = $result.CodeCoverage.CoveragePercent + if ($coveragePercent -lt 100) { + throw "Pester suite '$($suite.Name)' achieved $coveragePercent% coverage, below required 100%." + } +} + +if (-not $SkipOciTests) { + Write-Host '=== Running .NET 10 OCI Artifact tool tests ===' + $ociConfig = New-PesterConfiguration + $ociConfig.Run.Path = Join-Path $repoRoot 'tests/OciArtifact.Tests.ps1' + $ociConfig.Run.PassThru = $true + $ociConfig.Output.Verbosity = 'Normal' + $ociResult = Invoke-Pester -Configuration $ociConfig + if ($ociResult.FailedCount -gt 0) { + throw "OCI artifact test suite failed with $($ociResult.FailedCount) failing test(s)." + } +} + +Write-Host 'All unit test suites passed with 100% measured PowerShell coverage.' diff --git a/tools/OciArtifact.cs b/tools/OciArtifact.cs new file mode 100644 index 0000000..bceabd9 --- /dev/null +++ b/tools/OciArtifact.cs @@ -0,0 +1,1196 @@ +#:property TargetFramework=net10.0 +#:property Nullable=enable +#:property PublishAot=false + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Formats.Tar; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; + +namespace Codebelt.Docfx; + +internal static class OciArtifact +{ + private const string OciIndexMediaType = "application/vnd.oci.image.index.v1+json"; + private const string DefaultSourceUrl = "https://github.com/codebeltnet/docfx"; + private const string SpdxPredicateType = "https://spdx.dev/Document"; + private const string SlsaPredicatePrefix = "https://slsa.dev/provenance/"; + private const long DefaultPartSizeBytes = 1024L * 1024L * 1024L; // 1 GiB + private const long MaxCachedJsonBytes = 32L * 1024L * 1024L; + + private static readonly UTF8Encoding Utf8NoBom = new(false); + private static readonly Regex Sha256HexPattern = new(@"^[0-9a-f]{64}$", RegexOptions.CultureInvariant); + private static readonly Regex Sha256AnyCasePattern = new(@"^[0-9a-fA-F]{64}$", RegexOptions.CultureInvariant); + private static readonly Regex CommitShaPattern = new(@"^[0-9a-f]{40}$", RegexOptions.CultureInvariant); + private static readonly Regex PartNamePattern = new(@"^[A-Za-z0-9_.-]+\.oci\.part\d{3}$", RegexOptions.CultureInvariant); + + private static int Main(string[] args) + { + try + { + if (args.Length == 0) + { + throw new InvalidDataException("Expected a command: verify, merge, loaded-config, seal, check-seal, split, reassemble, or extract-layout."); + } + + var command = args[0]; + var rest = args[1..]; + + switch (command) + { + case "verify": + RunVerify(rest); + break; + case "merge": + RunMerge(rest); + break; + case "loaded-config": + RunLoadedConfig(rest); + break; + case "seal": + RunSeal(rest); + break; + case "check-seal": + RunCheckSeal(rest); + break; + case "split": + RunSplit(rest); + break; + case "reassemble": + RunReassemble(rest); + break; + case "extract-layout": + RunExtractLayout(rest); + break; + default: + throw new InvalidDataException($"Unknown command '{command}'."); + } + + return 0; + } + catch (Exception error) + { + Console.Error.WriteLine(error.Message); + return 1; + } + } + + private static void Require([DoesNotReturnIf(false)] bool condition, string message) + { + if (!condition) + { + throw new InvalidDataException(message); + } + } + + private static (List Positionals, Dictionary> Options) ParseArgs(string[] args, HashSet? flagOptions = null) + { + var positionals = new List(); + var options = new Dictionary>(StringComparer.Ordinal); + flagOptions ??= new HashSet(StringComparer.Ordinal); + + for (var i = 0; i < args.Length; i++) + { + var token = args[i]; + if (token.StartsWith("--", StringComparison.Ordinal)) + { + if (flagOptions.Contains(token)) + { + if (!options.TryGetValue(token, out var flags)) + { + flags = new List(); + options[token] = flags; + } + flags.Add("true"); + } + else + { + Require(i + 1 < args.Length, $"Missing value for option '{token}'."); + var value = args[++i]; + if (!options.TryGetValue(token, out var list)) + { + list = new List(); + options[token] = list; + } + list.Add(value); + } + } + else + { + positionals.Add(token); + } + } + + return (positionals, options); + } + + private static string? GetOption(Dictionary> options, string name) + => options.TryGetValue(name, out var values) && values.Count > 0 ? values[^1] : null; + + private static string GetRequiredOption(Dictionary> options, string name) + { + var value = GetOption(options, name); + Require(!string.IsNullOrWhiteSpace(value), $"Option '{name}' is required."); + return value!; + } + + private static bool HasFlag(Dictionary> options, string name) + => options.ContainsKey(name); + + private static string ComputeFileSha256(string path) + { + using var stream = File.OpenRead(path); + return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant(); + } + + private static string ComputeBytesSha256(byte[] bytes) + => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); + + private static void WriteSeal(string archivePath, string? checksumPath = null) + { + var fullArchive = Path.GetFullPath(archivePath); + Require(File.Exists(fullArchive) && new FileInfo(fullArchive).Length > 0, $"OCI archive is missing or empty: {fullArchive}"); + var target = checksumPath is null ? fullArchive + ".sha256" : Path.GetFullPath(checksumPath); + var digest = ComputeFileSha256(fullArchive); + var fileName = Path.GetFileName(fullArchive); + File.WriteAllText(target, $"{digest} {fileName}\n", Utf8NoBom); + } + + private static string CheckSeal(string archivePath, string? checksumPath = null) + { + var fullArchive = Path.GetFullPath(archivePath); + var fullChecksum = checksumPath is null ? fullArchive + ".sha256" : Path.GetFullPath(checksumPath); + Require(File.Exists(fullArchive) && new FileInfo(fullArchive).Length > 0, $"OCI archive is missing or empty: {fullArchive}"); + Require(File.Exists(fullChecksum), $"OCI archive checksum is missing: {fullChecksum}"); + + var line = File.ReadAllText(fullChecksum, Encoding.UTF8).Trim(); + var fields = line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + Require(fields.Length == 2 && Sha256AnyCasePattern.IsMatch(fields[0]), + "The checksum file must contain one GNU-style SHA-256 checksum record."); + + var recordedName = fields[1].TrimStart('*'); + Require(string.Equals(Path.GetFileName(recordedName), Path.GetFileName(fullArchive), StringComparison.Ordinal), + $"The checksum file names '{recordedName}', expected '{Path.GetFileName(fullArchive)}'."); + + var actual = ComputeFileSha256(fullArchive); + Require(string.Equals(actual, fields[0], StringComparison.OrdinalIgnoreCase), + $"Archive checksum mismatch: expected {fields[0].ToLowerInvariant()}, found {actual}."); + return actual; + } + + private static void RunSeal(string[] args) + { + var (positionals, options) = ParseArgs(args); + Require(positionals.Count == 1, "Expected archive path."); + var archive = Path.GetFullPath(positionals[0]); + var checksumPath = GetOption(options, "--checksum"); + WriteSeal(archive, checksumPath); + var digest = ComputeFileSha256(archive); + Console.WriteLine(JsonSerializer.Serialize(new { archiveSha256 = digest })); + } + + private static void RunCheckSeal(string[] args) + { + var (positionals, options) = ParseArgs(args); + Require(positionals.Count == 1, "Expected archive path."); + var archive = Path.GetFullPath(positionals[0]); + var checksumPath = GetOption(options, "--checksum"); + var digest = CheckSeal(archive, checksumPath); + Console.WriteLine(JsonSerializer.Serialize(new { archiveSha256 = digest })); + } + + private static VerificationIdentity ReadIdentity(Dictionary> options) + { + var version = GetRequiredOption(options, "--version"); + var docfxVersion = GetRequiredOption(options, "--docfx-version"); + var revision = GetRequiredOption(options, "--revision"); + var source = GetOption(options, "--source") ?? DefaultSourceUrl; + var platform = GetOption(options, "--platform"); + + Require(CommitShaPattern.IsMatch(revision), "The source revision must be a lowercase 40-character commit SHA."); + if (platform is not null) + { + Require(platform is "amd64" or "arm64", $"Unsupported platform '{platform}'. Expected 'amd64' or 'arm64'."); + } + + return new VerificationIdentity(version, docfxVersion, revision, source, platform); + } + + private static void RunVerify(string[] args) + { + var (positionals, options) = ParseArgs(args, new HashSet(StringComparer.Ordinal) { "--no-seal", "--check-seal" }); + Require(positionals.Count == 1, "Expected archive path."); + var archivePath = Path.GetFullPath(positionals[0]); + var identity = ReadIdentity(options); + var expectedDigest = GetOption(options, "--expected-digest"); + + if (HasFlag(options, "--check-seal")) + { + CheckSeal(archivePath); + } + + var archive = OciArchive.Open(archivePath); + var expectedPlatforms = identity.Platform is not null + ? new[] { identity.Platform } + : new[] { "amd64", "arm64" }; + + var result = archive.Verify(identity, expectedPlatforms, expectedDigest); + + if (!HasFlag(options, "--no-seal")) + { + WriteSeal(archivePath); + } + + var archiveSha256 = ComputeFileSha256(archivePath); + Console.WriteLine(JsonSerializer.Serialize(new + { + indexDigest = result.IndexDigest, + archiveSha256, + platforms = result.Platforms, + configs = result.Configs + })); + } + + private static void RunMerge(string[] args) + { + var (positionals, options) = ParseArgs(args, new HashSet(StringComparer.Ordinal) { "--no-input-seal" }); + Require(positionals.Count == 1, "Expected output archive path."); + var outputPath = Path.GetFullPath(positionals[0]); + var identity = ReadIdentity(options); + Require(options.TryGetValue("--input", out var inputPaths) && inputPaths.Count > 0, "At least one --input archive is required."); + + var checkInputSeal = !HasFlag(options, "--no-input-seal"); + var expectedPlatforms = identity.Platform is not null + ? new[] { identity.Platform } + : new[] { "amd64", "arm64" }; + + var inputs = new List<(string Path, OciArchive Archive, string Architecture)>(); + var mergedManifests = new JsonArray(); + var seenArchitectures = new HashSet(StringComparer.Ordinal); + + foreach (var rawInput in inputPaths) + { + var fullInput = Path.GetFullPath(rawInput); + if (checkInputSeal) + { + CheckSeal(fullInput); + } + + var archive = OciArchive.Open(fullInput); + var runnableArchs = archive.GetRunnableArchitectures(); + Require(runnableArchs.Count == 1, $"Expected one tested platform per input archive, found {runnableArchs.Count} in '{fullInput}'."); + var arch = runnableArchs[0]; + Require(seenArchitectures.Add(arch), $"Duplicate input platform '{arch}'."); + + archive.Verify(identity, new[] { arch }, null); + + foreach (var manifest in archive.IndexElement.GetProperty("manifests").EnumerateArray()) + { + mergedManifests.Add(JsonNode.Parse(manifest.GetRawText())); + } + + inputs.Add((fullInput, archive, arch)); + } + + var missing = expectedPlatforms.Where(p => !seenArchitectures.Contains(p)).ToArray(); + Require(missing.Length == 0 && seenArchitectures.Count == expectedPlatforms.Length, + $"Unexpected platform inventory for merge: [{string.Join(", ", seenArchitectures.Order(StringComparer.Ordinal))}]."); + + var embeddedIndexNode = new JsonObject + { + ["schemaVersion"] = 2, + ["mediaType"] = OciIndexMediaType, + ["manifests"] = mergedManifests, + ["annotations"] = new JsonObject + { + ["org.opencontainers.image.version"] = identity.Version, + ["org.opencontainers.image.revision"] = identity.Revision, + ["net.codebelt.docfx.engine.version"] = identity.Version, + ["net.codebelt.docfx.cli.version"] = identity.DocfxVersion + } + }; + + var embeddedIndexBytes = Encoding.UTF8.GetBytes(embeddedIndexNode.ToJsonString(new JsonSerializerOptions { WriteIndented = false })); + var embeddedIndexHex = ComputeBytesSha256(embeddedIndexBytes); + var embeddedIndexDigest = "sha256:" + embeddedIndexHex; + + var layoutIndexNode = new JsonObject + { + ["schemaVersion"] = 2, + ["mediaType"] = OciIndexMediaType, + ["manifests"] = new JsonArray + { + new JsonObject + { + ["mediaType"] = OciIndexMediaType, + ["digest"] = embeddedIndexDigest, + ["size"] = embeddedIndexBytes.LongLength, + ["annotations"] = new JsonObject + { + ["org.opencontainers.image.ref.name"] = identity.Version + } + } + } + }; + + var layoutIndexBytes = Encoding.UTF8.GetBytes(layoutIndexNode.ToJsonString(new JsonSerializerOptions { WriteIndented = false })); + var ociLayoutBytes = Encoding.UTF8.GetBytes("{\"imageLayoutVersion\":\"1.0.0\"}"); + + var outputDir = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + var seenBlobs = new HashSet(StringComparer.Ordinal); + using (var outputStream = File.Create(outputPath)) + using (var writer = new TarWriter(outputStream, TarEntryFormat.Pax, leaveOpen: false)) + { + foreach (var input in inputs) + { + using var inputStream = File.OpenRead(input.Path); + using var reader = new TarReader(inputStream, leaveOpen: false); + TarEntry? entry; + while ((entry = reader.GetNextEntry(copyData: false)) is not null) + { + if (entry.EntryType == TarEntryType.Directory) + { + continue; + } + + var normalized = NormalizeMemberName(entry.Name); + if (!normalized.StartsWith("blobs/sha256/", StringComparison.Ordinal)) + { + continue; + } + + if (!seenBlobs.Add(normalized)) + { + continue; + } + + Require(entry.DataStream is not null, $"OCI archive entry '{normalized}' has no data."); + var outEntry = new PaxTarEntry(TarEntryType.RegularFile, normalized) + { + DataStream = entry.DataStream + }; + writer.WriteEntry(outEntry); + } + } + + if (seenBlobs.Add("blobs/sha256/" + embeddedIndexHex)) + { + WriteBytesEntry(writer, "blobs/sha256/" + embeddedIndexHex, embeddedIndexBytes); + } + WriteBytesEntry(writer, "index.json", layoutIndexBytes); + WriteBytesEntry(writer, "oci-layout", ociLayoutBytes); + } + + // Re-verify the assembled multi-platform archive end-to-end before sealing. + var verified = OciArchive.Open(outputPath).Verify(identity, expectedPlatforms, embeddedIndexDigest); + WriteSeal(outputPath); + var archiveSha256 = ComputeFileSha256(outputPath); + var archiveBytes = new FileInfo(outputPath).Length; + + Console.WriteLine(JsonSerializer.Serialize(new + { + indexDigest = verified.IndexDigest, + archiveSha256, + archiveBytes, + platforms = verified.Platforms, + configs = verified.Configs + })); + } + + private static void RunLoadedConfig(string[] args) + { + var (positionals, options) = ParseArgs(args); + Require(positionals.Count == 1, "Expected archive path."); + var archivePath = Path.GetFullPath(positionals[0]); + var platform = GetRequiredOption(options, "--platform"); + var image = GetRequiredOption(options, "--image"); + var context = GetOption(options, "--context"); + + Require(platform is "amd64" or "arm64", $"Unsupported platform '{platform}'."); + + var archive = OciArchive.Open(archivePath); + var expectedConfigDigest = archive.GetPlatformConfigDigest(platform); + var expectedHex = expectedConfigDigest["sha256:".Length..]; + + var psi = new ProcessStartInfo("docker") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }; + if (!string.IsNullOrWhiteSpace(context)) + { + psi.ArgumentList.Add("--context"); + psi.ArgumentList.Add(context); + } + psi.ArgumentList.Add("image"); + psi.ArgumentList.Add("save"); + psi.ArgumentList.Add(image); + + using var process = Process.Start(psi) ?? throw new InvalidOperationException("Unable to start docker image save."); + var stderrTask = process.StandardError.ReadToEndAsync(); + var found = false; + + try + { + using var reader = new TarReader(process.StandardOutput.BaseStream, leaveOpen: false); + TarEntry? entry; + while ((entry = reader.GetNextEntry(copyData: false)) is not null) + { + if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile)) + { + continue; + } + + var normalized = entry.Name.StartsWith("./", StringComparison.Ordinal) ? entry.Name[2..] : entry.Name; + if (string.Equals(normalized, "blobs/sha256/" + expectedHex, StringComparison.Ordinal) + || string.Equals(normalized, expectedHex + ".json", StringComparison.Ordinal)) + { + Require(entry.DataStream is not null, "Saved Docker config entry has no data."); + var actualHex = Convert.ToHexString(SHA256.HashData(entry.DataStream)).ToLowerInvariant(); + Require(string.Equals("sha256:" + actualHex, expectedConfigDigest, StringComparison.Ordinal), + "Loaded config bytes changed."); + found = true; + } + } + } + finally + { + if (!process.HasExited) + { + process.WaitForExit(); + } + } + + var stderr = stderrTask.GetAwaiter().GetResult().Trim(); + Require(process.ExitCode == 0 && found, + $"Loaded config differs from exported OCI artifact{(string.IsNullOrEmpty(stderr) ? string.Empty : ": " + stderr)}."); + + Console.WriteLine(expectedConfigDigest); + } + + private static void RunSplit(string[] args) + { + var (positionals, options) = ParseArgs(args, new HashSet(StringComparer.Ordinal) { "--write-checksum" }); + Require(positionals.Count == 1, "Expected archive path."); + var archivePath = Path.GetFullPath(positionals[0]); + var outputDir = Path.GetFullPath(GetRequiredOption(options, "--output-dir")); + var prefix = GetRequiredOption(options, "--prefix"); + var partSizeOption = GetOption(options, "--part-size"); + var partSize = partSizeOption is null ? DefaultPartSizeBytes : long.Parse(partSizeOption); + + Require(File.Exists(archivePath) && new FileInfo(archivePath).Length > 0, $"OCI archive is missing or empty: {archivePath}"); + Require(partSize > 0, "Part size must be a positive integer."); + Require(Regex.IsMatch(prefix, @"^[A-Za-z0-9_.-]+$", RegexOptions.CultureInvariant), $"Invalid asset prefix '{prefix}'."); + + Directory.CreateDirectory(outputDir); + + var pieces = new List(); + using var fullHasher = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[1024 * 1024]; + long totalBytes = 0; + + using (var source = File.OpenRead(archivePath)) + { + var partIndex = 0; + while (true) + { + var read = source.Read(buffer, 0, (int)Math.Min(buffer.Length, partSize)); + if (read == 0) + { + break; + } + + var partName = $"{prefix}.oci.part{partIndex:D3}"; + var partPath = Path.Combine(outputDir, partName); + long partBytes = 0; + using var partHasher = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + + using (var target = File.Create(partPath)) + { + while (read > 0) + { + target.Write(buffer, 0, read); + partHasher.AppendData(buffer, 0, read); + fullHasher.AppendData(buffer, 0, read); + partBytes += read; + totalBytes += read; + + var remaining = partSize - partBytes; + if (remaining <= 0) + { + break; + } + + read = source.Read(buffer, 0, (int)Math.Min(buffer.Length, remaining)); + } + } + + pieces.Add(new + { + name = partName, + sha256 = Convert.ToHexString(partHasher.GetHashAndReset()).ToLowerInvariant(), + size = partBytes + }); + partIndex++; + } + } + + var archiveSha256 = Convert.ToHexString(fullHasher.GetHashAndReset()).ToLowerInvariant(); + if (HasFlag(options, "--write-checksum")) + { + var checksumFile = Path.Combine(outputDir, Path.GetFileName(archivePath) + ".sha256"); + File.WriteAllText(checksumFile, $"{archiveSha256} {Path.GetFileName(archivePath)}\n", Utf8NoBom); + } + + Console.WriteLine(JsonSerializer.Serialize(new + { + archiveSha256, + archiveBytes = totalBytes, + pieces + })); + } + + private static void RunReassemble(string[] args) + { + var (_, options) = ParseArgs(args); + var manifestPath = Path.GetFullPath(GetRequiredOption(options, "--manifest")); + var inputDir = Path.GetFullPath(GetRequiredOption(options, "--input-dir")); + var outputPath = Path.GetFullPath(GetRequiredOption(options, "--output")); + var checksumPath = GetOption(options, "--checksum"); + + Require(File.Exists(manifestPath), $"Release manifest is missing: {manifestPath}"); + using var document = JsonDocument.Parse(File.ReadAllText(manifestPath, Encoding.UTF8)); + var root = document.RootElement; + + var expectedArchiveSha = ReadStringCaseInsensitive(root, "ArchiveSha256"); + Require(!string.IsNullOrEmpty(expectedArchiveSha) && Sha256HexPattern.IsMatch(expectedArchiveSha), + "Release manifest does not contain a valid ArchiveSha256."); + + var expectedArchiveBytes = ReadInt64CaseInsensitive(root, "ArchiveBytes"); + var piecesElement = GetPropertyCaseInsensitive(root, "Pieces"); + Require(piecesElement.ValueKind == JsonValueKind.Array && piecesElement.GetArrayLength() > 0, + "Release manifest must contain at least one archive piece."); + + var outputDir = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(outputDir)) + { + Directory.CreateDirectory(outputDir); + } + + using var fullHasher = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[1024 * 1024]; + long totalBytes = 0; + + using (var output = File.Create(outputPath)) + { + foreach (var piece in piecesElement.EnumerateArray()) + { + var name = ReadStringCaseInsensitive(piece, "Name"); + var expectedPieceSha = ReadStringCaseInsensitive(piece, "Sha256"); + var expectedPieceSize = ReadInt64CaseInsensitive(piece, "Size"); + + Require(!string.IsNullOrEmpty(name) && PartNamePattern.IsMatch(name), $"Invalid piece identity '{name}'."); + Require(!string.IsNullOrEmpty(expectedPieceSha) && Sha256HexPattern.IsMatch(expectedPieceSha), + $"Invalid piece checksum for '{name}'."); + Require(expectedPieceSize.HasValue && expectedPieceSize.Value > 0, $"Invalid piece size for '{name}'."); + + var piecePath = Path.Combine(inputDir, name); + Require(File.Exists(piecePath), $"Missing release archive piece: {piecePath}"); + + using var partHasher = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + long actualPieceBytes = 0; + + using (var source = File.OpenRead(piecePath)) + { + int read; + while ((read = source.Read(buffer, 0, buffer.Length)) > 0) + { + output.Write(buffer, 0, read); + partHasher.AppendData(buffer, 0, read); + fullHasher.AppendData(buffer, 0, read); + actualPieceBytes += read; + totalBytes += read; + } + } + + var actualPieceSha = Convert.ToHexString(partHasher.GetHashAndReset()).ToLowerInvariant(); + Require(actualPieceBytes == expectedPieceSize.Value && string.Equals(actualPieceSha, expectedPieceSha, StringComparison.Ordinal), + $"Piece '{name}' differs from verified release record."); + } + } + + var actualArchiveSha = Convert.ToHexString(fullHasher.GetHashAndReset()).ToLowerInvariant(); + Require(string.Equals(actualArchiveSha, expectedArchiveSha, StringComparison.Ordinal), + $"Reassembled archive checksum mismatch: expected {expectedArchiveSha}, found {actualArchiveSha}."); + if (expectedArchiveBytes.HasValue) + { + Require(totalBytes == expectedArchiveBytes.Value, + $"Reassembled archive size mismatch: expected {expectedArchiveBytes.Value}, found {totalBytes}."); + } + + if (checksumPath is not null) + { + CheckSeal(outputPath, checksumPath); + } + + WriteSeal(outputPath); + Console.WriteLine(JsonSerializer.Serialize(new + { + archiveSha256 = actualArchiveSha, + archiveBytes = totalBytes + })); + } + + private static void RunExtractLayout(string[] args) + { + var (positionals, options) = ParseArgs(args); + Require(positionals.Count == 1, "Expected archive path."); + var archivePath = Path.GetFullPath(positionals[0]); + var outputDir = Path.GetFullPath(GetRequiredOption(options, "--output-dir")); + + // Verify tar structure and every blob SHA-256 before materializing. + _ = OciArchive.Open(archivePath); + Directory.CreateDirectory(outputDir); + + using var stream = File.OpenRead(archivePath); + using var reader = new TarReader(stream, leaveOpen: false); + TarEntry? entry; + while ((entry = reader.GetNextEntry(copyData: false)) is not null) + { + if (entry.EntryType == TarEntryType.Directory) + { + continue; + } + + var normalized = NormalizeMemberName(entry.Name); + var relative = normalized.Replace('/', Path.DirectorySeparatorChar); + var targetPath = Path.GetFullPath(Path.Combine(outputDir, relative)); + var fullOutputDir = outputDir.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + Require(targetPath.StartsWith(fullOutputDir, StringComparison.Ordinal), $"Unsafe extraction path '{normalized}'."); + + var parent = Path.GetDirectoryName(targetPath); + if (!string.IsNullOrEmpty(parent)) + { + Directory.CreateDirectory(parent); + } + + Require(entry.DataStream is not null, $"OCI archive entry '{normalized}' has no data."); + using var target = File.Create(targetPath); + entry.DataStream.CopyTo(target); + } + + Console.WriteLine(JsonSerializer.Serialize(new { layoutPath = outputDir })); + } + + private static void WriteBytesEntry(TarWriter writer, string name, byte[] data) + { + using var memory = new MemoryStream(data, writable: false); + var entry = new PaxTarEntry(TarEntryType.RegularFile, name) + { + DataStream = memory + }; + writer.WriteEntry(entry); + } + + private static string NormalizeMemberName(string rawName) + { + var name = rawName.StartsWith("./", StringComparison.Ordinal) ? rawName[2..] : rawName; + Require(!string.IsNullOrEmpty(name) + && !name.Contains('\\') + && !name.StartsWith('/') + && !name.Split('/').Contains("..", StringComparer.Ordinal), + $"Unsafe OCI archive member '{rawName}'."); + return name; + } + + private static JsonElement GetPropertyCaseInsensitive(JsonElement element, string name) + { + if (element.ValueKind != JsonValueKind.Object) + { + return default; + } + foreach (var property in element.EnumerateObject()) + { + if (string.Equals(property.Name, name, StringComparison.OrdinalIgnoreCase)) + { + return property.Value; + } + } + return default; + } + + private static string? ReadStringCaseInsensitive(JsonElement element, string name) + { + var prop = GetPropertyCaseInsensitive(element, name); + return prop.ValueKind == JsonValueKind.String ? prop.GetString() : null; + } + + private static long? ReadInt64CaseInsensitive(JsonElement element, string name) + { + var prop = GetPropertyCaseInsensitive(element, name); + return prop.ValueKind == JsonValueKind.Number && prop.TryGetInt64(out var value) ? value : null; + } + + private sealed record VerificationIdentity( + string Version, + string DocfxVersion, + string Revision, + string Source, + string? Platform); + + private sealed record VerificationResult( + string IndexDigest, + string[] Platforms, + Dictionary Configs); + + private sealed class OciArchive + { + private readonly string _path; + private readonly Dictionary _memberSizes; + private readonly Dictionary _cachedMembers; + private readonly byte[] _indexBytes; + private readonly JsonDocument _indexDocument; + + public JsonElement IndexElement => _indexDocument.RootElement; + + private OciArchive( + string path, + Dictionary memberSizes, + Dictionary cachedMembers, + byte[] indexBytes, + JsonDocument indexDocument) + { + _path = path; + _memberSizes = memberSizes; + _cachedMembers = cachedMembers; + _indexBytes = indexBytes; + _indexDocument = indexDocument; + } + + public static OciArchive Open(string path) + { + Require(File.Exists(path) && new FileInfo(path).Length > 0, $"OCI archive is missing or empty: {path}"); + + var memberSizes = new Dictionary(StringComparer.Ordinal); + var cachedMembers = new Dictionary(StringComparer.Ordinal); + var buffer = new byte[1024 * 1024]; + + using (var stream = File.OpenRead(path)) + using (var reader = new TarReader(stream, leaveOpen: false)) + { + TarEntry? entry; + while ((entry = reader.GetNextEntry(copyData: false)) is not null) + { + if (entry.EntryType == TarEntryType.Directory) + { + continue; + } + + Require(entry.EntryType is TarEntryType.RegularFile or TarEntryType.V7RegularFile, + $"Unsafe tar member type '{entry.EntryType}' for '{entry.Name}'."); + + var name = NormalizeMemberName(entry.Name); + Require(!memberSizes.ContainsKey(name), $"Duplicate tar member '{name}'."); + + var isBlob = name.StartsWith("blobs/sha256/", StringComparison.Ordinal); + Require(name is "index.json" or "oci-layout" || isBlob, + $"Unexpected OCI archive member '{name}'."); + + if (isBlob) + { + var expectedHex = name["blobs/sha256/".Length..]; + Require(Sha256HexPattern.IsMatch(expectedHex), $"Invalid OCI blob path '{name}'."); + } + + Require(entry.DataStream is not null, $"OCI archive entry '{name}' has no data."); + + long actualSize = 0; + using var hasher = isBlob ? IncrementalHash.CreateHash(HashAlgorithmName.SHA256) : null; + MemoryStream? memory = null; + var shouldCache = name is "index.json" or "oci-layout" || entry.Length <= MaxCachedJsonBytes; + var isJsonCandidate = name is "index.json" or "oci-layout"; + + if (shouldCache) + { + memory = new MemoryStream(); + } + + int read; + while ((read = entry.DataStream.Read(buffer, 0, buffer.Length)) > 0) + { + if (actualSize == 0 && !isJsonCandidate && buffer[0] == (byte)'{') + { + isJsonCandidate = true; + } + + hasher?.AppendData(buffer, 0, read); + actualSize += read; + + if (memory is not null) + { + if (isJsonCandidate && actualSize <= MaxCachedJsonBytes) + { + memory.Write(buffer, 0, read); + } + else + { + memory.Dispose(); + memory = null; + } + } + } + + if (isBlob) + { + var actualHex = Convert.ToHexString(hasher!.GetHashAndReset()).ToLowerInvariant(); + Require(string.Equals(name, "blobs/sha256/" + actualHex, StringComparison.Ordinal), + $"Corrupt OCI blob '{name}': actual digest sha256:{actualHex}."); + } + + memberSizes[name] = actualSize; + if (memory is not null) + { + cachedMembers[name] = memory.ToArray(); + memory.Dispose(); + } + } + } + + Require(memberSizes.ContainsKey("oci-layout"), "Missing oci-layout member."); + Require(memberSizes.ContainsKey("index.json"), "Missing index.json member."); + + using (var layoutDoc = JsonDocument.Parse(cachedMembers["oci-layout"])) + { + var layoutRoot = layoutDoc.RootElement; + Require(layoutRoot.ValueKind == JsonValueKind.Object + && layoutRoot.TryGetProperty("imageLayoutVersion", out var v) + && v.ValueKind == JsonValueKind.String + && v.GetString() == "1.0.0", + "Invalid OCI layout."); + } + + var indexBytes = cachedMembers["index.json"]; + var indexDoc = JsonDocument.Parse(indexBytes); + + // Buildx exports a layout index that wraps the actual OCI image index. + while (indexDoc.RootElement.ValueKind == JsonValueKind.Object + && indexDoc.RootElement.TryGetProperty("manifests", out var manifests) + && manifests.ValueKind == JsonValueKind.Array + && manifests.GetArrayLength() == 1 + && ReadString(manifests[0], "mediaType") == OciIndexMediaType) + { + var descriptor = manifests[0]; + var blobBytes = ReadDescriptorBytes(path, memberSizes, cachedMembers, descriptor); + indexDoc.Dispose(); + indexBytes = blobBytes; + indexDoc = JsonDocument.Parse(indexBytes); + } + + Require(ReadInt32(indexDoc.RootElement, "schemaVersion") == 2 + && ReadString(indexDoc.RootElement, "mediaType") == OciIndexMediaType, + "Expected an OCI image index."); + + return new OciArchive(path, memberSizes, cachedMembers, indexBytes, indexDoc); + } + + private static byte[] ReadDescriptorBytes( + string path, + Dictionary memberSizes, + Dictionary cachedMembers, + JsonElement descriptor) + { + var digest = ReadString(descriptor, "digest"); + var size = ReadInt64(descriptor, "size"); + Require(!string.IsNullOrEmpty(digest) && digest.StartsWith("sha256:", StringComparison.Ordinal) + && Sha256HexPattern.IsMatch(digest["sha256:".Length..]), + $"Invalid OCI descriptor digest '{digest}'."); + var blobName = "blobs/sha256/" + digest["sha256:".Length..]; + Require(memberSizes.TryGetValue(blobName, out var actualSize) && size.HasValue && actualSize == size.Value, + $"Missing or truncated OCI content '{blobName}'."); + + if (cachedMembers.TryGetValue(blobName, out var cached)) + { + return cached; + } + + using var stream = File.OpenRead(path); + using var reader = new TarReader(stream, leaveOpen: false); + TarEntry? entry; + while ((entry = reader.GetNextEntry(copyData: false)) is not null) + { + if (entry.EntryType == TarEntryType.Directory) + { + continue; + } + if (string.Equals(NormalizeMemberName(entry.Name), blobName, StringComparison.Ordinal)) + { + using var memory = new MemoryStream(); + entry.DataStream!.CopyTo(memory); + return memory.ToArray(); + } + } + + throw new InvalidDataException($"Missing OCI content '{blobName}'."); + } + + private JsonDocument ReadBlobJson(JsonElement descriptor) + { + var bytes = ReadDescriptorBytes(_path, _memberSizes, _cachedMembers, descriptor); + return JsonDocument.Parse(bytes); + } + + public List GetRunnableArchitectures() + { + var architectures = new List(); + foreach (var descriptor in GetArray(IndexElement, "manifests")) + { + var platform = GetProperty(descriptor, "platform"); + if (ReadString(platform, "os") == "linux") + { + var arch = ReadString(platform, "architecture"); + Require(!string.IsNullOrEmpty(arch), "Runnable manifest is missing platform.architecture."); + architectures.Add(arch!); + } + } + return architectures; + } + + public string GetPlatformConfigDigest(string architecture) + { + var matches = GetArray(IndexElement, "manifests") + .Where(d => + { + var p = GetProperty(d, "platform"); + return ReadString(p, "os") == "linux" && ReadString(p, "architecture") == architecture; + }) + .ToArray(); + Require(matches.Length == 1, $"Expected one manifest for linux/{architecture}, found {matches.Length}."); + using var manifestDoc = ReadBlobJson(matches[0]); + var config = GetProperty(manifestDoc.RootElement, "config"); + var digest = ReadString(config, "digest"); + Require(!string.IsNullOrEmpty(digest) && digest.StartsWith("sha256:", StringComparison.Ordinal), + "Manifest config is missing a valid SHA-256 digest."); + return digest!; + } + + public VerificationResult Verify(VerificationIdentity identity, string[] expectedPlatforms, string? expectedIndexDigest) + { + var indexDigest = "sha256:" + ComputeBytesSha256(_indexBytes); + if (!string.IsNullOrEmpty(expectedIndexDigest)) + { + Require(string.Equals(indexDigest, expectedIndexDigest, StringComparison.Ordinal), + $"Saved OCI index digest mismatch: expected {expectedIndexDigest}, found {indexDigest}."); + } + + var manifests = GetArray(IndexElement, "manifests"); + var runnable = manifests.Where(d => ReadString(GetProperty(d, "platform"), "os") == "linux").ToArray(); + var actualPlatforms = runnable + .Select(d => ReadString(GetProperty(d, "platform"), "architecture") ?? string.Empty) + .Order(StringComparer.Ordinal) + .ToArray(); + var sortedExpected = expectedPlatforms.Order(StringComparer.Ordinal).ToArray(); + Require(actualPlatforms.SequenceEqual(sortedExpected, StringComparer.Ordinal), + $"Unexpected platform inventory: [{string.Join(", ", actualPlatforms)}], expected [{string.Join(", ", sortedExpected)}]."); + + var runnableDigests = runnable + .Select(d => ReadString(d, "digest") ?? string.Empty) + .ToHashSet(StringComparer.Ordinal); + + foreach (var descriptor in manifests) + { + var platform = GetProperty(descriptor, "platform"); + if (ReadString(platform, "os") == "linux") + { + continue; + } + + var annotations = GetProperty(descriptor, "annotations"); + Require(ReadString(platform, "os") == "unknown" + && ReadString(platform, "architecture") == "unknown" + && ReadString(annotations, "vnd.docker.reference.type") == "attestation-manifest" + && runnableDigests.Contains(ReadString(annotations, "vnd.docker.reference.digest") ?? string.Empty), + "Unexpected runtime or unattached attestation in image index."); + } + + var configs = new Dictionary(StringComparer.Ordinal); + + foreach (var descriptor in runnable) + { + var arch = ReadString(GetProperty(descriptor, "platform"), "architecture")!; + var manifestDigest = ReadString(descriptor, "digest")!; + var manifestHex = manifestDigest["sha256:".Length..]; + + using var manifestDoc = ReadBlobJson(descriptor); + var manifestRoot = manifestDoc.RootElement; + var configDescriptor = GetProperty(manifestRoot, "config"); + var configDigest = ReadString(configDescriptor, "digest")!; + using var configDoc = ReadBlobJson(configDescriptor); + var configRoot = configDoc.RootElement; + + Require(ReadString(configRoot, "os") == "linux" + && ReadString(configRoot, "architecture") == arch, + $"Config CPU mismatch for {arch}."); + + var labels = GetProperty(GetProperty(configRoot, "config"), "Labels"); + var requiredLabels = new Dictionary(StringComparer.Ordinal) + { + ["org.opencontainers.image.source"] = identity.Source, + ["org.opencontainers.image.revision"] = identity.Revision, + ["org.opencontainers.image.version"] = identity.Version, + ["net.codebelt.docfx.engine.version"] = identity.Version, + ["net.codebelt.docfx.cli.version"] = identity.DocfxVersion + }; + + foreach (var (key, expectedValue) in requiredLabels) + { + var actualValue = ReadString(labels, key); + Require(string.Equals(actualValue, expectedValue, StringComparison.Ordinal), + $"Identity mismatch: label '{key}' expected '{expectedValue}', found '{actualValue ?? string.Empty}'."); + } + + Require(!string.IsNullOrWhiteSpace(ReadString(labels, "org.opencontainers.image.created")), + "Missing build identity: org.opencontainers.image.created."); + + foreach (var layer in GetArray(manifestRoot, "layers")) + { + var layerDigest = ReadString(layer, "digest"); + var layerSize = ReadInt64(layer, "size"); + Require(!string.IsNullOrEmpty(layerDigest) && layerDigest.StartsWith("sha256:", StringComparison.Ordinal), + "Invalid image layer descriptor."); + var blobName = "blobs/sha256/" + layerDigest["sha256:".Length..]; + Require(_memberSizes.TryGetValue(blobName, out var actualSize) && layerSize.HasValue && actualSize == layerSize.Value, + $"Missing or truncated image layer '{blobName}'."); + } + + var predicates = new HashSet(StringComparer.Ordinal); + foreach (var attestationDescriptor in manifests) + { + var annotations = GetProperty(attestationDescriptor, "annotations"); + if (!string.Equals(ReadString(annotations, "vnd.docker.reference.digest"), manifestDigest, StringComparison.Ordinal)) + { + continue; + } + + using var attDoc = ReadBlobJson(attestationDescriptor); + foreach (var layer in GetArray(attDoc.RootElement, "layers")) + { + using var statementDoc = ReadBlobJson(layer); + var statement = statementDoc.RootElement; + + var subjectMatches = GetArray(statement, "subject") + .Any(s => string.Equals(ReadString(GetProperty(s, "digest"), "sha256"), manifestHex, StringComparison.Ordinal)); + Require(subjectMatches, "Attestation subject mismatch."); + + var predicateType = ReadString(statement, "predicateType"); + Require(!string.IsNullOrEmpty(predicateType), "Attestation statement missing predicateType."); + var predicate = GetProperty(statement, "predicate"); + + if (predicateType == SpdxPredicateType) + { + Require(!string.IsNullOrWhiteSpace(ReadString(predicate, "spdxVersion")) + && GetArray(predicate, "packages").Length > 0, + "Empty SBOM."); + } + else if (predicateType!.StartsWith(SlsaPredicatePrefix, StringComparison.Ordinal)) + { + var hasBuildType = !string.IsNullOrWhiteSpace(ReadString(predicate, "buildType")); + var buildDef = GetProperty(predicate, "buildDefinition"); + Require(hasBuildType || buildDef.ValueKind == JsonValueKind.Object, "Empty provenance."); + + var parameters = GetProperty(GetProperty(GetProperty(buildDef, "externalParameters"), "request"), "args"); + if (parameters.ValueKind != JsonValueKind.Object) + { + parameters = GetProperty(GetProperty(GetProperty(predicate, "invocation"), "parameters"), "args"); + } + + var expectedArgs = new Dictionary(StringComparer.Ordinal) + { + ["build-arg:DOCFX_VERSION"] = identity.DocfxVersion, + ["label:org.opencontainers.image.version"] = identity.Version, + ["label:net.codebelt.docfx.engine.version"] = identity.Version, + ["label:net.codebelt.docfx.cli.version"] = identity.DocfxVersion, + ["label:org.opencontainers.image.revision"] = identity.Revision, + ["label:org.opencontainers.image.source"] = identity.Source + }; + + foreach (var (argKey, argExpected) in expectedArgs) + { + var actualArg = ReadString(parameters, argKey); + Require(string.Equals(actualArg, argExpected, StringComparison.Ordinal), + $"Provenance build identity mismatch: {argKey}."); + } + } + + predicates.Add(predicateType!); + } + } + + Require(predicates.Contains(SpdxPredicateType) + && predicates.Any(p => p.StartsWith(SlsaPredicatePrefix, StringComparison.Ordinal)), + $"SBOM or provenance missing for {arch}."); + + configs[arch] = configDigest; + } + + return new VerificationResult(indexDigest, actualPlatforms, configs); + } + + private static JsonElement[] GetArray(JsonElement value, string propertyName) + { + if (value.ValueKind == JsonValueKind.Object + && value.TryGetProperty(propertyName, out var property) + && property.ValueKind == JsonValueKind.Array) + { + return property.EnumerateArray().ToArray(); + } + return Array.Empty(); + } + + private static JsonElement GetProperty(JsonElement value, string propertyName) + { + if (value.ValueKind == JsonValueKind.Object + && value.TryGetProperty(propertyName, out var property)) + { + return property; + } + return default; + } + + private static string? ReadString(JsonElement value, string propertyName) + { + return value.ValueKind == JsonValueKind.Object + && value.TryGetProperty(propertyName, out var property) + && property.ValueKind == JsonValueKind.String + ? property.GetString() + : null; + } + + private static int? ReadInt32(JsonElement value, string propertyName) + { + return value.ValueKind == JsonValueKind.Object + && value.TryGetProperty(propertyName, out var property) + && property.TryGetInt32(out var number) + ? number + : null; + } + + private static long? ReadInt64(JsonElement value, string propertyName) + { + return value.ValueKind == JsonValueKind.Object + && value.TryGetProperty(propertyName, out var property) + && property.TryGetInt64(out var number) + ? number + : null; + } + } +}