diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7386681f..21c0f5be 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,15 +10,36 @@ on: pull_request: branches: [main] +permissions: + contents: read + jobs: + changes: + runs-on: windows-latest + outputs: + docs_only: ${{ steps.classify.outputs.docs_only }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Classify the entire PR diff + id: classify + run: python eng\ci\classify_changes.py + format: + needs: changes runs-on: windows-latest steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable + if: needs.changes.outputs.docs_only == 'false' with: components: rustfmt - name: Check Rust formatting + if: needs.changes.outputs.docs_only == 'false' shell: pwsh run: | cargo fmt --all -- --check @@ -26,10 +47,36 @@ jobs: Write-Error "Rust formatting failed. Run 'cargo fmt --all' and commit the changes." exit 1 } + - uses: actions/setup-node@v4 + with: + node-version: 24 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Test CI scheduling and artifact contracts + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + python -m pip install -r eng\ci\requirements.txt --quiet + python -m unittest discover -s eng\ci -p "test_*.py" -v + node --test bindings\js\scripts\run-codegen.test.mjs + .\tests\e2e\e2e_preparation.tests.ps1 + .\tests\e2e\prebuilt_codegen.tests.ps1 + - name: Validate checked-in release notes + shell: pwsh + run: | + .\eng\release\validate_release_notes.ps1 + .\eng\release\test_validate_release_notes.ps1 + - name: Validate Python package source metadata + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + python eng\release\python\verify_python_release.py source - # Tests - test: - needs: format + # Rust test programs are independent builds, not reusable runtime packages. + test-rust: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] runs-on: windows-latest steps: - uses: actions/checkout@v4 @@ -247,9 +294,33 @@ jobs: - name: Check x86 Classic COM runtime run: cargo check -p jswinrt_rs --target i686-pc-windows-msvc - # E2E tests: winmd → generate → call real WinRT APIs - e2e: - needs: test + # Producers start beside Rust tests. Only current-run, configuration-specific + # payloads are reusable; neither a Cargo target tree nor a test program is shared. + build-codegen-x64: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - name: Build x64 codegen + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + cargo build -p dynwinrt-codegen --release --target x86_64-pc-windows-msvc + New-Item -ItemType Directory artifacts\codegen-x64\payload -Force | Out-Null + Copy-Item target\x86_64-pc-windows-msvc\release\dynwinrt-codegen.exe artifacts\codegen-x64\payload + .\eng\ci\artifact.ps1 -Mode Write -Path artifacts\codegen-x64 -Kind codegen -Architecture x64 + - uses: actions/upload-artifact@v4 + with: + name: ci-codegen-x64 + path: artifacts\codegen-x64 + if-no-files-found: error + retention-days: 7 + + build-bindings-x64: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] runs-on: windows-latest steps: - uses: actions/checkout@v4 @@ -260,6 +331,164 @@ jobs: - uses: actions/setup-python@v5 with: python-version: "3.12" + architecture: x64 + - name: Build production JS binding + working-directory: bindings/js + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + npm install + npx napi build --no-const-enum --platform --release --target x86_64-pc-windows-msvc -o dist + npm run build:entrypoints --silent + node scripts\verify-runtime-artifact.mjs dist + - name: Stage production JS artifact + shell: pwsh + run: | + New-Item -ItemType Directory artifacts\js-x64 -Force | Out-Null + Copy-Item bindings\js\dist artifacts\js-x64\payload -Recurse + .\eng\ci\artifact.ps1 -Mode Write -Path artifacts\js-x64 -Kind js -Architecture x64 + - uses: actions/upload-artifact@v4 + with: + name: ci-js-x64 + path: artifacts\js-x64 + if-no-files-found: error + retention-days: 7 + - name: Build Python binding + working-directory: bindings/py + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + python -m pip install "maturin>=1.11,<2" --quiet + python -m maturin build --quiet --interpreter python --target x86_64-pc-windows-msvc ` + --out ..\..\artifacts\python-x64\payload + ..\..\eng\ci\artifact.ps1 -Mode Write -Path ..\..\artifacts\python-x64 ` + -Kind python -Architecture x64 -Profile dev -PythonAbi cp312 + - uses: actions/upload-artifact@v4 + with: + name: ci-python-x64 + path: artifacts\python-x64 + if-no-files-found: error + retention-days: 7 + + build-js-test-hooks: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Build isolated JS native fixtures + working-directory: bindings/js + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + npm install + npx napi build --no-const-enum --platform --release --target x86_64-pc-windows-msvc --features test-hooks -o dist + npm run build:entrypoints --silent + node scripts\verify-runtime-artifact.mjs dist --test-hooks + - name: Stage test-hooks artifact + shell: pwsh + run: | + New-Item -ItemType Directory artifacts\js-test-hooks-x64 -Force | Out-Null + Copy-Item bindings\js\dist artifacts\js-test-hooks-x64\payload -Recurse + .\eng\ci\artifact.ps1 -Mode Write -Path artifacts\js-test-hooks-x64 ` + -Kind js -Architecture x64 -Features test-hooks + - uses: actions/upload-artifact@v4 + with: + name: ci-js-test-hooks-x64 + path: artifacts\js-test-hooks-x64 + if-no-files-found: error + retention-days: 7 + + build-arm64: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, format] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-pc-windows-msvc + - uses: actions/setup-node@v4 + with: + node-version: 24 + - name: Build ARM64 codegen + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + cargo build -p dynwinrt-codegen --release --target aarch64-pc-windows-msvc + New-Item -ItemType Directory artifacts\codegen-arm64\payload -Force | Out-Null + Copy-Item target\aarch64-pc-windows-msvc\release\dynwinrt-codegen.exe artifacts\codegen-arm64\payload + .\eng\ci\artifact.ps1 -Mode Write -Path artifacts\codegen-arm64 -Kind codegen -Architecture arm64 + - uses: actions/upload-artifact@v4 + with: + name: ci-codegen-arm64 + path: artifacts\codegen-arm64 + if-no-files-found: error + retention-days: 7 + - name: Build production ARM64 JS binding + working-directory: bindings/js + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + npm install + npx napi build --no-const-enum --platform --release --target aarch64-pc-windows-msvc -o dist + npm run build:entrypoints --silent + - name: Stage ARM64 JS artifact + shell: pwsh + run: | + New-Item -ItemType Directory artifacts\js-arm64 -Force | Out-Null + Copy-Item bindings\js\dist artifacts\js-arm64\payload -Recurse + .\eng\ci\artifact.ps1 -Mode Write -Path artifacts\js-arm64 -Kind js -Architecture arm64 + - name: Compile raw union MSVC C oracle for ARM64 + run: cargo test -p jswinrt_rs --features test-hooks --target aarch64-pc-windows-msvc --no-run + - uses: actions/upload-artifact@v4 + with: + name: ci-js-arm64 + path: artifacts\js-arm64 + if-no-files-found: error + retention-days: 7 + + # Production E2E never waits for the ARM64 lane or the Rust test job. + e2e-runtime: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, build-codegen-x64, build-bindings-x64] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-node@v4 + with: + node-version: 24 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + architecture: x64 + - uses: actions/download-artifact@v4 + with: + name: ci-codegen-x64 + path: artifacts\codegen-x64 + - uses: actions/download-artifact@v4 + with: + name: ci-js-x64 + path: artifacts\js-x64 + - uses: actions/download-artifact@v4 + with: + name: ci-python-x64 + path: artifacts\python-x64 + - name: Verify production input artifacts + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\codegen-x64 -Kind codegen -Architecture x64 + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\js-x64 -Kind js -Architecture x64 + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\python-x64 -Kind python -Architecture x64 -Profile dev -PythonAbi cp312 + Copy-Item artifacts\js-x64\payload bindings\js\dist -Recurse + node bindings\js\scripts\verify-runtime-artifact.mjs bindings\js\dist + "DYNWINRT_CODEGEN=$((Resolve-Path artifacts\codegen-x64\payload\dynwinrt-codegen.exe).Path)" >> $env:GITHUB_ENV - uses: NuGet/setup-nuget@v2 - name: Install Win32 metadata shell: pwsh @@ -277,36 +506,32 @@ jobs: } "DYNWINRT_WIN32_WINMD=$($winmd.FullName)" >> $env:GITHUB_ENV "DYNWINRT_REQUIRE_WIN32_METADATA=1" >> $env:GITHUB_ENV - - name: Build dynwinrt-codegen - run: cargo build -p dynwinrt-codegen --release - - name: Build JS binding + - name: Install JS test dependencies working-directory: bindings/js - run: | - npm install - npx napi build --no-const-enum --platform --release -o dist - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - npm run build:entrypoints --silent - npm install --no-save tsx + run: npm install - name: Test JS binding working-directory: bindings/js run: npm test - - name: Build Python binding + - name: Install prebuilt Python binding + shell: pwsh run: | - cd bindings/py - python -m venv .venv - .venv/Scripts/Activate.ps1 - pip install pytest maturin "mypy>=1.13,<2" "coverage>=7.15,<8" --quiet - maturin build --quiet - pip install (Get-ChildItem ../../target/wheels/*.whl | Sort-Object LastWriteTime -Descending | Select-Object -First 1).FullName --force-reinstall --quiet + $PSNativeCommandUseErrorActionPreference = $true + python -m venv bindings\py\.venv + $python = '.\bindings\py\.venv\Scripts\python.exe' + & $python -m pip install pytest "mypy>=1.13,<2" "coverage>=7.15,<8" --quiet + $wheels = @(Get-ChildItem artifacts\python-x64\payload -Filter *.whl -File) + if ($wheels.Count -ne 1) { throw 'Expected exactly the verified CPython 3.12 x64 wheel' } + & $python -m pip install $wheels[0].FullName --no-deps --no-index --quiet - name: Test Python binding run: | .\bindings\py\.venv\Scripts\python.exe -m pytest bindings\py\tests -q + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } .\bindings\py\.venv\Scripts\python.exe -m mypy.stubtest dynwinrt --allowlist bindings\py\stubtest_allowlist.txt --ignore-disjoint-bases - name: Test generated Python long paths run: | .\eng\release\python\test_generated_python_long_paths.ps1 ` -Python .\bindings\py\.venv\Scripts\python.exe ` - -Codegen .\target\release\dynwinrt-codegen.exe + -Codegen $env:DYNWINRT_CODEGEN - name: Test generated implementation symbol identities shell: pwsh run: | @@ -314,7 +539,7 @@ jobs: $env:DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME = '1' cargo test -p dynwinrt-codegen --test implementation_naming_test - name: Run E2E tests - run: .\tests\e2e\e2e_test.ps1 -SkipBuild + run: .\tests\e2e\e2e_test.ps1 -SkipBuild -Codegen $env:DYNWINRT_CODEGEN # This optional-SDK behavioral smoke is separate from generated coverage # totals. The receiver/GIL regressions also run in instrumented core and # binding tests; no WinAppSDK runtime bootstrap or UI loop is needed here. @@ -340,93 +565,244 @@ jobs: -Filter Windows.winmd -File -Recurse | Sort-Object FullName -Descending | Select-Object -First 1 if (-not $windows) { throw 'Windows SDK metadata is required for the dispatcher smoke' } $output = Join-Path $PWD 'artifacts\dispatcher-implementation-smoke' - .\target\release\dynwinrt-codegen.exe generate ` + & $env:DYNWINRT_CODEGEN generate ` --winmd (Join-Path $metadata 'Microsoft.UI.winmd') --ref $windows.FullName ` --namespace Microsoft.UI.Dispatching --class-name DispatcherQueue ` --lang py --output $output if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } .\bindings\py\.venv\Scripts\python.exe .\tests\e2e\runners\dispatcher_implementation_py.py --generated $output + + e2e-native: + if: needs.changes.outputs.docs_only == 'false' + needs: [changes, build-codegen-x64, build-js-test-hooks] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + - uses: actions/download-artifact@v4 + with: + name: ci-codegen-x64 + path: artifacts\codegen-x64 + - uses: actions/download-artifact@v4 + with: + name: ci-js-test-hooks-x64 + path: artifacts\js-test-hooks-x64 + - name: Verify isolated native fixture artifacts + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\codegen-x64 -Kind codegen -Architecture x64 + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\js-test-hooks-x64 -Kind js -Architecture x64 -Features test-hooks + Copy-Item artifacts\js-test-hooks-x64\payload bindings\js\dist -Recurse + node bindings\js\scripts\verify-runtime-artifact.mjs bindings\js\dist --test-hooks + "DYNWINRT_CODEGEN=$((Resolve-Path artifacts\codegen-x64\payload\dynwinrt-codegen.exe).Path)" >> $env:GITHUB_ENV + - name: Install JS test dependencies + working-directory: bindings/js + run: npm install + - uses: NuGet/setup-nuget@v2 + - name: Install Win32 metadata + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + $root = Join-Path $env:RUNNER_TEMP 'win32metadata' + nuget install Microsoft.Windows.SDK.Win32Metadata ` + -Version 71.0.14-preview -OutputDirectory $root -DirectDownload -NonInteractive + $winmd = Get-ChildItem $root -Filter Windows.Win32.winmd -File -Recurse | Select-Object -First 1 + if (-not $winmd) { throw 'Microsoft.Windows.SDK.Win32Metadata did not contain Windows.Win32.winmd' } + "DYNWINRT_WIN32_WINMD=$($winmd.FullName)" >> $env:GITHUB_ENV + "DYNWINRT_REQUIRE_WIN32_METADATA=1" >> $env:GITHUB_ENV + # These execute the same tests as the developer npm scripts, but must not + # run their build:test-hooks prefixes over the downloaded immutable inputs. - name: Test JS TSFN lifecycle and queue handling working-directory: bindings/js - run: npm run test:tsfn + run: npx --no-install ava __test__/tsfn.spec.ts - name: Test actual generated unsafe COM companion working-directory: bindings/js - run: npm run test:generated-unsafe + run: npx --no-install ava __test__/generated-unsafe-companion.e2e.ts - name: Test metadata-driven native COM one-shot completion working-directory: bindings/js - run: npm run test:native-completion + run: npx --no-install ava __test__/native-completion.e2e.ts - name: Test metadata-driven COM borrowed copies working-directory: bindings/js - run: npm run test:borrowed-copy + run: npx --no-install ava __test__/borrowed-copy.e2e.ts - name: Test Win32 failed-cleanup recovery working-directory: bindings/js run: node --expose-gc __test__\fixtures\win32-cleanup-errors.cjs - # dynwinrt-codegen (x64 + arm64) + # Stable check identities also complete on intentional documentation-only skips. + test: + if: ${{ always() }} + needs: [changes, format, test-rust] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: Require Rust validation + env: + NEEDS: ${{ toJSON(needs) }} + REQUIRED_JOBS: changes,format,test-rust + DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} + DOCS_SKIPPABLE_JOBS: test-rust + run: | + .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` + -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') + + e2e: + if: ${{ always() }} + needs: + [ + changes, + format, + test, + build-codegen-x64, + build-bindings-x64, + build-js-test-hooks, + e2e-runtime, + e2e-native, + ] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: Require all E2E lanes + env: + NEEDS: ${{ toJSON(needs) }} + REQUIRED_JOBS: changes,format,test,build-codegen-x64,build-bindings-x64,build-js-test-hooks,e2e-runtime,e2e-native + DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} + DOCS_SKIPPABLE_JOBS: build-codegen-x64,build-bindings-x64,build-js-test-hooks,e2e-runtime,e2e-native + run: | + .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` + -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') + + # Only these gated assembly jobs publish the existing release-ready names. dynwinrt-codegen: - needs: test + if: ${{ always() }} + needs: [changes, test, e2e, build-codegen-x64, build-arm64] runs-on: windows-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - with: - targets: aarch64-pc-windows-msvc - - name: Build x64 + - name: Require all validation + env: + NEEDS: ${{ toJSON(needs) }} + REQUIRED_JOBS: changes,test,e2e,build-codegen-x64,build-arm64 + DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} + DOCS_SKIPPABLE_JOBS: build-codegen-x64,build-arm64 run: | - cargo build -p dynwinrt-codegen --release - mkdir -p tools/dynwinrt-codegen/npm/bin/x64 - cp target/release/dynwinrt-codegen.exe tools/dynwinrt-codegen/npm/bin/x64/ - - name: Build arm64 + .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` + -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') + - uses: actions/download-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' + with: + name: ci-codegen-x64 + path: artifacts\codegen-x64 + - uses: actions/download-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' + with: + name: ci-codegen-arm64 + path: artifacts\codegen-arm64 + - name: Assemble verified codegen package + if: needs.changes.outputs.docs_only == 'false' + shell: pwsh run: | - cargo build -p dynwinrt-codegen --release --target aarch64-pc-windows-msvc - mkdir -p tools/dynwinrt-codegen/npm/bin/arm64 - cp target/aarch64-pc-windows-msvc/release/dynwinrt-codegen.exe tools/dynwinrt-codegen/npm/bin/arm64/ + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\codegen-x64 -Kind codegen -Architecture x64 + .\eng\ci\artifact.ps1 -Mode Verify -Path artifacts\codegen-arm64 -Kind codegen -Architecture arm64 + foreach ($arch in @('x64', 'arm64')) { + New-Item -ItemType Directory "tools\dynwinrt-codegen\npm\bin\$arch" -Force | Out-Null + Copy-Item "artifacts\codegen-$arch\payload\dynwinrt-codegen.exe" "tools\dynwinrt-codegen\npm\bin\$arch" + } - uses: actions/upload-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' with: name: dynwinrt-codegen path: tools/dynwinrt-codegen/npm/ + if-no-files-found: error - # dynwinrt (x64 + arm64 in one job) dynwinrt: - needs: test + if: ${{ always() }} + needs: [changes, test, e2e, build-bindings-x64, build-arm64] runs-on: windows-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - with: - targets: aarch64-pc-windows-msvc + - name: Require all validation + env: + NEEDS: ${{ toJSON(needs) }} + REQUIRED_JOBS: changes,test,e2e,build-bindings-x64,build-arm64 + DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} + DOCS_SKIPPABLE_JOBS: build-bindings-x64,build-arm64 + run: | + .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` + -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') - uses: actions/setup-node@v4 + if: needs.changes.outputs.docs_only == 'false' with: node-version: 24 - - name: Install dependencies + - uses: actions/download-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' + with: + name: ci-js-x64 + path: artifacts\js-x64 + - uses: actions/download-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' + with: + name: ci-js-arm64 + path: artifacts\js-arm64 + - name: Assemble matching production runtime sidecars + if: needs.changes.outputs.docs_only == 'false' + run: .\eng\ci\merge-runtime-artifacts.ps1 -X64 artifacts\js-x64 -Arm64 artifacts\js-arm64 -Output bindings\js\dist + - name: Install import test dependencies + if: needs.changes.outputs.docs_only == 'false' working-directory: bindings/js run: npm install - - name: Compile raw union MSVC C oracle for ARM64 - run: cargo test -p jswinrt_rs --features test-hooks --target aarch64-pc-windows-msvc --no-run - - name: Build x64 - working-directory: bindings/js - run: | - npx napi build --no-const-enum --platform --release -o dist - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - npm run build:entrypoints --silent - - name: Build arm64 - working-directory: bindings/js - run: | - npx napi build --no-const-enum --platform --release --target aarch64-pc-windows-msvc -o dist - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - npm run build:entrypoints --silent - name: Check production native imports + if: needs.changes.outputs.docs_only == 'false' working-directory: bindings/js run: npm run test:imports + - name: Verify assembled JS runtime artifact + if: needs.changes.outputs.docs_only == 'false' + run: node .\bindings\js\scripts\verify-runtime-artifact.mjs .\bindings\js\dist - uses: actions/upload-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' with: name: dynwinrt path: bindings/js/dist/ if-no-files-found: error - uses: actions/download-artifact@v4 + if: needs.changes.outputs.docs_only == 'false' with: name: dynwinrt path: ${{ runner.temp }}\dynwinrt-artifact - name: Verify downloaded JS runtime artifact + if: needs.changes.outputs.docs_only == 'false' shell: pwsh run: node .\bindings\js\scripts\verify-runtime-artifact.mjs "$env:RUNNER_TEMP\dynwinrt-artifact" + + ci-success: + if: ${{ always() }} + needs: + [ + changes, + format, + test-rust, + test, + build-codegen-x64, + build-bindings-x64, + build-js-test-hooks, + build-arm64, + e2e-runtime, + e2e-native, + e2e, + dynwinrt, + dynwinrt-codegen, + ] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: Require every Build job + env: + NEEDS: ${{ toJSON(needs) }} + REQUIRED_JOBS: changes,format,test-rust,test,build-codegen-x64,build-bindings-x64,build-js-test-hooks,build-arm64,e2e-runtime,e2e-native,e2e,dynwinrt,dynwinrt-codegen + DOCS_ONLY: ${{ needs.changes.outputs.docs_only }} + DOCS_SKIPPABLE_JOBS: test-rust,build-codegen-x64,build-bindings-x64,build-js-test-hooks,build-arm64,e2e-runtime,e2e-native + run: | + .\eng\ci\assert-success.ps1 -NeedsJson $env:NEEDS -RequiredJobs ($env:REQUIRED_JOBS -split ',') ` + -DocsOnly $env:DOCS_ONLY -SkippableJobs ($env:DOCS_SKIPPABLE_JOBS -split ',') diff --git a/.pipelines/release.yml b/.pipelines/release.yml index 5a7f3d04..4ed54926 100644 --- a/.pipelines/release.yml +++ b/.pipelines/release.yml @@ -55,6 +55,18 @@ extends: - checkout: self fetchDepth: 0 + - task: PowerShell@2 + displayName: Validate GitHub release notes + inputs: + targetType: filePath + filePath: eng/release/validate_release_notes.ps1 + + - task: PowerShell@2 + displayName: Test GitHub release notes validation + inputs: + targetType: filePath + filePath: eng/release/test_validate_release_notes.ps1 + - task: UseNode@1 displayName: Setup Node.js 24 inputs: @@ -193,11 +205,10 @@ extends: $tag = "$(Build.SourceBranchName)" $version = $tag -replace '^v', '' $isPrerelease = if ($version -match '-') { 'true' } else { 'false' } - $releaseLabel = if ($isPrerelease -eq 'true') { 'Prerelease' } else { 'Release' } + Write-Host "Publishing version: $version" echo "##vso[task.setvariable variable=version;isOutput=true]$version" echo "##vso[task.setvariable variable=isPrerelease;isOutput=true]$isPrerelease" - echo "##vso[task.setvariable variable=releaseLabel;isOutput=true]$releaseLabel" # Update package.json versions $jsPackage = Get-Content "bindings/js/package.json" | ConvertFrom-Json @@ -325,7 +336,6 @@ extends: variables: version: $[ stageDependencies.Build.Build.outputs['SetMeta.version'] ] isPrerelease: $[ stageDependencies.Build.Build.outputs['SetMeta.isPrerelease'] ] - releaseLabel: $[ stageDependencies.Build.Build.outputs['SetMeta.releaseLabel'] ] jobs: - job: create_github_release pool: @@ -342,6 +352,9 @@ extends: artifactName: npm-packages targetPath: $(Pipeline.Workspace)/npm-packages steps: + - checkout: self + fetchDepth: 1 + - task: GitHubRelease@1 displayName: Create GitHub Release inputs: @@ -352,33 +365,8 @@ extends: tagSource: 'userSpecifiedTag' tag: 'v$(version)' title: 'v$(version)' - releaseNotesSource: 'inline' - releaseNotesInline: | - ## $(releaseLabel) v$(version) - - **Packages:** - - `@microsoft/dynwinrt` - JavaScript/TypeScript bindings for WinRT dynamic invocation - - `@microsoft/dynwinrt-codegen` - Code generation tool for typed WinRT bindings - - `dynwinrt` - Native Python runtime for generated WinRT projections - - `dynwinrt-codegen` - Standalone Python code generation tool - - ## Installation - - ```bash - npm install @microsoft/dynwinrt - npm install -D @microsoft/dynwinrt-codegen - python -m pip install --pre dynwinrt dynwinrt-codegen - ``` - - ## What's Included - - - ✅ Native addons for x64 and ARM64 - - ✅ TypeScript type definitions - - ✅ dynwinrt-codegen CLI for code generation - - ✅ CPython 3.11–3.14 runtime wheels for Windows x64 and ARM64 - - ✅ Standalone Python codegen wheels for Windows x64 and ARM64 - - For usage instructions, see the [README](https://github.com/microsoft/dynwinrt#readme). + releaseNotesSource: 'filePath' + releaseNotesFilePath: '$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md' assets: '$(Pipeline.Workspace)/npm-packages/*.tgz' isDraft: false isPreRelease: $(isPrerelease) diff --git a/README.md b/README.md index b8b8f12a..b54a8abb 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,9 @@ builds, test suites, and contribution guidelines. ## Contributing +See the [Build CI guide](docs/guides/development/ci.md) for parallel validation, +artifact reuse, documentation-only PR checks, and running E2E with a prebuilt generator. + This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit . When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. diff --git a/bindings/js/__test__/borrowed-copy.e2e.ts b/bindings/js/__test__/borrowed-copy.e2e.ts index 9858dce8..29a9663c 100644 --- a/bindings/js/__test__/borrowed-copy.e2e.ts +++ b/bindings/js/__test__/borrowed-copy.e2e.ts @@ -5,6 +5,7 @@ import test from 'ava' import { spawnSync } from 'node:child_process' import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { join, resolve } from 'node:path' +import { runCodegen } from '../scripts/run-codegen.mjs' const packageRoot = resolve(process.cwd()) const repositoryRoot = resolve(packageRoot, '..', '..') @@ -15,11 +16,6 @@ test.before((t) => { t.truthy(winmd, 'Pinned DYNWINRT_WIN32_WINMD is required') rmSync(output, { recursive: true, force: true }) const args = [ - 'run', - '--quiet', - '-p', - 'dynwinrt-codegen', - '--', 'generate', '--winmd', winmd!, @@ -29,7 +25,7 @@ test.before((t) => { output, ] for (const extra of [['--dry-run'], []]) { - const generated = spawnSync('cargo', [...args, ...extra], { + const generated = runCodegen([...args, ...extra], { cwd: repositoryRoot, encoding: 'utf8', windowsHide: true, diff --git a/bindings/js/__test__/generated-unsafe-companion.e2e.ts b/bindings/js/__test__/generated-unsafe-companion.e2e.ts index 6505a9ca..c8beb16a 100644 --- a/bindings/js/__test__/generated-unsafe-companion.e2e.ts +++ b/bindings/js/__test__/generated-unsafe-companion.e2e.ts @@ -6,6 +6,7 @@ import { spawnSync } from 'node:child_process' import { lstatSync, readFileSync, readlinkSync, rmSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs' import { basename, dirname, join, resolve } from 'node:path' import { pathToFileURL } from 'node:url' +import { runCodegen } from '../scripts/run-codegen.mjs' test.serial('generated IUIAutomation unsafe companion parses and registers without native calls', (t) => { const winmd = process.env.DYNWINRT_WIN32_WINMD @@ -17,14 +18,8 @@ test.serial('generated IUIAutomation unsafe companion parses and registers witho ) try { - const generation = spawnSync( - 'cargo', + const generation = runCodegen( [ - 'run', - '--quiet', - '-p', - 'dynwinrt-codegen', - '--', 'generate', '--winmd', winmd!, @@ -141,11 +136,6 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr try { const generationArgs = [ - 'run', - '--quiet', - '-p', - 'dynwinrt-codegen', - '--', 'generate', '--winmd', winmd!, @@ -155,7 +145,7 @@ test.serial('generated safe COM and unsafe WinML companions preserve exact contr output, ] const runGeneration = (extraEnv: NodeJS.ProcessEnv = {}) => - spawnSync('cargo', generationArgs, { + runCodegen(generationArgs, { cwd: repositoryRoot, encoding: 'utf8', env: { ...process.env, DYNWINRT_CODEGEN_TEST_STRATEGY_RUNTIME: '1', ...extraEnv }, diff --git a/bindings/js/__test__/native-completion.e2e.ts b/bindings/js/__test__/native-completion.e2e.ts index 3a8dddb6..6e88dfd6 100644 --- a/bindings/js/__test__/native-completion.e2e.ts +++ b/bindings/js/__test__/native-completion.e2e.ts @@ -5,6 +5,7 @@ import test from 'ava' import { spawnSync } from 'node:child_process' import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { join, resolve } from 'node:path' +import { runCodegen } from '../scripts/run-codegen.mjs' const packageRoot = resolve(process.cwd()) const repositoryRoot = resolve(packageRoot, '..', '..') @@ -17,11 +18,6 @@ test.before((t) => { t.truthy(winmd, 'DYNWINRT_WIN32_WINMD is required for exact native-completion generation') rmSync(output, { recursive: true, force: true }) const args = [ - 'run', - '--quiet', - '-p', - 'dynwinrt-codegen', - '--', 'generate', '--winmd', winmd!, @@ -30,28 +26,22 @@ test.before((t) => { '--output', output, ] - const dryRun = spawnSync('cargo', [...args, '--dry-run'], { + const dryRun = runCodegen([...args, '--dry-run'], { cwd: repositoryRoot, encoding: 'utf8', windowsHide: true, }) t.is(dryRun.status, 0, dryRun.stderr) t.regex(dryRun.stdout, /Would generate ActivateAudioInterfaceAsync/) - const generation = spawnSync('cargo', args, { + const generation = runCodegen(args, { cwd: repositoryRoot, encoding: 'utf8', windowsHide: true, }) t.is(generation.status, 0, generation.stderr) if (process.env.DYNWINRT_TEST_AUDIO_RENDER === '1') { - const renderDevice = spawnSync( - 'cargo', + const renderDevice = runCodegen( [ - 'run', - '--quiet', - '-p', - 'dynwinrt-codegen', - '--', 'generate', '--namespace', 'Windows.Media.Devices', diff --git a/bindings/js/scripts/run-codegen.d.mts b/bindings/js/scripts/run-codegen.d.mts new file mode 100644 index 00000000..c9b74066 --- /dev/null +++ b/bindings/js/scripts/run-codegen.d.mts @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { SpawnSyncOptionsWithStringEncoding, SpawnSyncReturns } from 'node:child_process' + +export declare function runCodegen( + args: string[], + options: SpawnSyncOptionsWithStringEncoding, +): SpawnSyncReturns diff --git a/bindings/js/scripts/run-codegen.mjs b/bindings/js/scripts/run-codegen.mjs new file mode 100644 index 00000000..96c53d0b --- /dev/null +++ b/bindings/js/scripts/run-codegen.mjs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { spawnSync } from 'node:child_process' +import { statSync } from 'node:fs' +import { resolve } from 'node:path' + +/** + * An explicit artifact path must never fall back to a local Cargo build. + * @param {string[]} args + * @param {import('node:child_process').SpawnSyncOptionsWithStringEncoding} options + */ +export function runCodegen(args, options) { + const codegen = (options.env ?? process.env).DYNWINRT_CODEGEN + if (codegen !== undefined) { + if (!codegen.trim()) throw new Error('DYNWINRT_CODEGEN must name a prebuilt dynwinrt-codegen executable') + const executable = resolve(options.cwd?.toString() ?? process.cwd(), codegen) + if (!statSync(executable).isFile()) throw new Error(`Prebuilt dynwinrt-codegen is not a file: ${executable}`) + const result = spawnSync(executable, args, options) + if (result.error) throw result.error + return result + } + return spawnSync('cargo', ['run', '--quiet', '-p', 'dynwinrt-codegen', '--', ...args], options) +} diff --git a/bindings/js/scripts/run-codegen.test.mjs b/bindings/js/scripts/run-codegen.test.mjs new file mode 100644 index 00000000..b2c4d84d --- /dev/null +++ b/bindings/js/scripts/run-codegen.test.mjs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import childProcess from 'node:child_process' +import { mkdtempSync, rmSync } from 'node:fs' +import { syncBuiltinESMExports } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { runCodegen } from './run-codegen.mjs' + +test('prebuilt invocation executes the selected file, arguments and environment without Cargo', () => { + const env = { ...process.env, DYNWINRT_CODEGEN: process.execPath, CODEGEN_SENTINEL: 'forwarded' } + const result = runCodegen(['-e', 'console.log(process.env.CODEGEN_SENTINEL); process.exit(23)'], { + encoding: 'utf8', + env, + windowsHide: true, + }) + assert.equal(result.status, 23) + assert.equal(result.stdout.trim(), 'forwarded') +}) + +test('an invalid executable reports its launch error without trying Cargo', (t) => { + const calls = [] + const error = new Error('not a valid executable') + t.mock.method(childProcess, 'spawnSync', (...args) => { + calls.push(args) + return { error, status: null, stdout: null, stderr: null } + }) + syncBuiltinESMExports() + try { + assert.throws( + () => runCodegen(['generate'], { encoding: 'utf8', env: { DYNWINRT_CODEGEN: process.execPath } }), + (actual) => actual === error, + ) + assert.equal(calls.length, 1) + assert.equal(calls[0][0], process.execPath) + } finally { + t.mock.restoreAll() + syncBuiltinESMExports() + } +}) + +test('invalid explicit paths never fall back; omission retains the developer Cargo command', (t) => { + const directory = mkdtempSync(join(tmpdir(), 'dynwinrt-codegen-selection-')) + const calls = [] + t.mock.method(childProcess, 'spawnSync', (...args) => { + calls.push(args) + return { status: 31, stdout: '', stderr: 'cargo boundary' } + }) + syncBuiltinESMExports() + try { + for (const path of ['', ' ', directory, join(directory, 'missing.exe')]) { + assert.throws(() => runCodegen(['generate'], { encoding: 'utf8', env: { DYNWINRT_CODEGEN: path } })) + } + assert.deepEqual(calls, []) + const options = { encoding: 'utf8', env: {}, cwd: directory } + assert.equal(runCodegen(['generate', '--output', 'a path with spaces'], options).status, 31) + assert.deepEqual(calls, [ + [ + 'cargo', + ['run', '--quiet', '-p', 'dynwinrt-codegen', '--', 'generate', '--output', 'a path with spaces'], + options, + ], + ]) + } finally { + t.mock.restoreAll() + syncBuiltinESMExports() + rmSync(directory, { recursive: true, force: true }) + } +}) diff --git a/docs/guides/development/ci.md b/docs/guides/development/ci.md new file mode 100644 index 00000000..7c727982 --- /dev/null +++ b/docs/guides/development/ci.md @@ -0,0 +1,124 @@ +# Build CI + +The `Build` workflow in `.github/workflows/build.yml` runs independent Rust +validation and native package builds in parallel. It does not change the +shipping Cargo release profile, coverage instrumentation, or the separate +Python release matrix. + +## Scheduling and artifacts + +After change classification and lightweight checks, full validation starts +these lanes without waiting for the Rust tests: + +| Job | Responsibility | +| --------------------- | ---------------------------------------------------------------------------------------------------------- | +| `test-rust` | Existing Rust unit, ABI, codegen, census, determinism, cleanup and live i686 checks | +| `build-codegen-x64` | Release x64 generator | +| `build-bindings-x64` | Production release x64 JS distribution and CPython 3.12 x64 development-profile wheel | +| `build-js-test-hooks` | Separate release x64 JS distribution with native test fixtures | +| `build-arm64` | Release ARM64 generator/runtime and the ARM64 C-oracle compile check | +| `e2e-runtime` | Production JS/Python tests, generated WinRT/COM/Win32/implementation E2E, long paths, and dispatcher smoke | +| `e2e-native` | TSFN, generated unsafe COM, native completion, borrowed copies, and Win32 cleanup fixtures | + +The two E2E consumers depend only on their x64 producers, not the ARM64 lane or +Rust tests. The original `test` and `e2e` check names aggregate their respective +validation lanes; the `e2e` aggregate retains its Rust-test prerequisite without +delaying either E2E consumer. `dynwinrt` and `dynwinrt-codegen` assemble the original +dual-architecture final artifacts only after Rust, E2E and the relevant builds +succeed. `ci-success` checks every job result, including final artifact +verification. Failure, cancellation, a missing result or an unexpected skip +fails these gates. + +Intermediate `ci-*` artifacts are inputs, **not release-ready packages**. +Downloads use the current workflow run. Each input includes a file-hash manifest +with the commit, run, package version, architecture, Cargo profile, feature set +and, for wheels, CPython ABI. Consumers verify it before using the payload. +The full JS distribution is transferred, including declarations and COM/Win32 +sidecars. Assembly requires identical architecture-independent files and keeps +both native binaries; it never overlays test-hook files onto production. + +Rust test executables still need their own `cargo test` builds. In particular, +the runtime-backed `implementation_naming_test` is not replaced by a generator +executable. Coverage binaries and the separate Python release workflow's +packaging configurations are not shared with production. + +## Documentation-only pull requests + +Pull requests that change only `.md` files take the lightweight path. The suffix +match is case-insensitive (`.MD` and `.mD` qualify), but does not include +`.markdown`, `.mdx`, or other file types. New Markdown files in any directory +qualify without editing a path list, including guides, sample and packaged +READMEs, release notes, and `docs/status` Markdown reports. + +There are currently no Markdown exclusions: the repository's Markdown is not +used as generator or native-test behavior input. Package READMEs and release +notes affect published descriptions, not native APIs, so they receive source +metadata and release-note checks rather than native rebuilds. A future +behavior-input exception must identify its exact file and actual consumer; +ordinary documentation must not acquire a directory-wide exclusion. + +Classification compares the PR merge base to its head using complete Git +history, not just the latest commit. Both old and new rename paths must qualify; +renaming code to Markdown or Markdown to code requires full validation. +Markdown additions, modifications and deletions qualify. Any non-Markdown +change, including JSON/CSV baselines, schemas, scripts, workflow files, sample +code/configuration, and unknown non-Markdown paths, requires full validation. +An empty diff uses full validation. Invalid statuses never select the +lightweight path; malformed or unavailable history fails classification +rather than guessing that the change is documentation-only. + +The lightweight path runs the scheduling, artifact, prebuilt-selection and +release-note configuration regressions, plus Python package source metadata +validation, without compiling native code. The metadata check validates README +declarations, presence and the same description headings checked in wheels; +it does not build wheels. Stable check names still run and validate the +explicitly expected heavy-job skips; no package artifact is created. Pushes +to `main` and version tags always use full validation. The workflow is not +hidden behind a top-level path filter. + +This policy selects jobs in `Build` only. The independent Coverage and Python +release workflows retain their own path filters and can still run for matching +Markdown paths. + +## Using a prebuilt generator locally + +Ordinary developer commands are unchanged: omitting a generator override uses +Cargo with the selected `-CargoProfile` and `-CargoTarget`. `-SkipBuild` alone +skips initial native builds, but still permits the existing Cargo generation +path. To prohibit generator rebuilds, supply a real executable explicitly: + +```powershell +.\tests\e2e\e2e_test.ps1 -SkipBuild ` + -Codegen C:\artifacts\dynwinrt-codegen.exe + +.\tests\e2e\e2e_test.ps1 -SkipBuild -Suite implementations ` + -Codegen C:\artifacts\dynwinrt-codegen.exe -Lang py,ts +``` + +`DYNWINRT_CODEGEN` provides the same default for both PowerShell entrypoints and +the JavaScript generated-unsafe, native-completion and borrowed-copy tests. +An explicit `-Codegen` takes precedence. Missing/invalid explicit files fail; +they never silently fall back to Cargo or a stale local binary. + +Binding artifacts must already be installed when using `-SkipBuild`: the full +matching JS distribution in `bindings\js\dist`, and a compatible wheel in the +selected Python environment. The JS fixture npm scripts retain their local +`build:test-hooks` behavior. CI instead runs their AVA tests directly against a +verified, separately downloaded test-hooks distribution. + +Run the lightweight regressions with: + +```powershell +python -m pip install -r eng\ci\requirements.txt +python -m unittest discover -s eng\ci -p "test_*.py" -v +node --test bindings\js\scripts\run-codegen.test.mjs +.\tests\e2e\e2e_preparation.tests.ps1 +.\tests\e2e\prebuilt_codegen.tests.ps1 +.\eng\release\validate_release_notes.ps1 +.\eng\release\test_validate_release_notes.ps1 +python eng\release\python\verify_python_release.py source +``` + +Parallelism removes the old Rust-test barrier and duplicate release builds; +actual hosted run times still depend on runner capacity and artifact transfer. +Measure completed runs before treating a wall-clock improvement as established. diff --git a/eng/ci/artifact.ps1 b/eng/ci/artifact.ps1 new file mode 100644 index 00000000..010ff8e9 --- /dev/null +++ b/eng/ci/artifact.ps1 @@ -0,0 +1,103 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [Parameter(Mandatory)][ValidateSet("Write", "Verify")][string]$Mode, + [Parameter(Mandatory)][string]$Path, + [Parameter(Mandatory)][ValidateSet("codegen", "js", "python")][string]$Kind, + [Parameter(Mandatory)][ValidateSet("x64", "arm64")][string]$Architecture, + [ValidateSet("release", "dev")][string]$Profile = "release", + [ValidateSet("production", "test-hooks")][string]$Features = "production", + [string]$PythonAbi +) + +$ErrorActionPreference = "Stop" +$repo = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +if (-not $env:GITHUB_SHA -or -not $env:GITHUB_RUN_ID) { + throw "Artifact identity requires GITHUB_SHA and GITHUB_RUN_ID." +} +$payload = (Get-Item -LiteralPath (Join-Path $Path "payload")).FullName +if (-not (Test-Path -LiteralPath $payload -PathType Container)) { + throw "Missing artifact payload directory: $payload" +} +$manifestPath = Join-Path $Path "manifest.json" +$version = if ($Kind -eq "js") { + (Get-Content -LiteralPath (Join-Path $repo "bindings\js\package.json") -Raw | ConvertFrom-Json).version +} else { + $cargo = if ($Kind -eq "codegen") { "tools\dynwinrt-codegen\Cargo.toml" } else { "bindings\py\Cargo.toml" } + $content = Get-Content -LiteralPath (Join-Path $repo $cargo) -Raw + $package = [regex]::Match($content, '(?ms)^\[package\]\r?\n(.*?)(?=^\[|\z)').Groups[1].Value + $versions = [regex]::Matches($package, '(?m)^version = "([^"]+)"\r?$') + if ($versions.Count -ne 1) { throw "Expected one package version in $cargo" } + $versions[0].Groups[1].Value +} +$target = if ($Architecture -eq "x64") { "x86_64-pc-windows-msvc" } else { "aarch64-pc-windows-msvc" } +$identity = [ordered]@{ + schema = 1 + commit = $env:GITHUB_SHA + run = $env:GITHUB_RUN_ID + kind = $Kind + version = $version + target = $target + profile = $Profile + features = $Features + pythonAbi = $PythonAbi +} +$files = [ordered]@{} +foreach ($file in (Get-ChildItem -LiteralPath $payload -File -Recurse | Sort-Object FullName)) { + $relative = [IO.Path]::GetRelativePath($payload, $file.FullName).Replace("\", "/") + $files[$relative] = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash +} +if ($files.Count -eq 0) { throw "Artifact payload is empty: $payload" } + +if ($Kind -eq "python") { + if ($Features -ne "production" -or $PythonAbi -notmatch '^cp3\d+$') { + throw "Python artifacts require a production wheel and an explicit CPython ABI." + } + $platform = if ($Architecture -eq "x64") { "win_amd64" } else { "win_arm64" } + $wheel = "dynwinrt-$version-$PythonAbi-$PythonAbi-$platform.whl" + if ($files.Count -ne 1 -or -not $files.Contains($wheel)) { + throw "Expected exactly the runtime wheel $wheel" + } +} else { + if ($PythonAbi) { throw "Only Python artifacts may specify a Python ABI." } + $native = if ($Kind -eq "codegen") { "dynwinrt-codegen.exe" } else { "dynwinrt.win32-$Architecture-msvc.node" } + if (-not $files.Contains($native)) { throw "Missing $native in $payload" } + $nativeFiles = @($files.Keys | Where-Object { $_ -match '\.(exe|node)$' }) + if ($nativeFiles.Count -ne 1) { throw "Expected one native binary in $payload" } + if ($Kind -eq "codegen" -and ($Features -ne "production" -or $files.Count -ne 1)) { + throw "Codegen artifacts must contain only the production executable." + } + $bytes = [IO.File]::ReadAllBytes((Join-Path $payload $native)) + if ($bytes.Length -lt 64 -or [BitConverter]::ToUInt16($bytes, 0) -ne 0x5a4d) { + throw "Invalid native PE artifact: $native" + } + $pe = [BitConverter]::ToInt32($bytes, 0x3c) + $machine = if ($Architecture -eq "x64") { 0x8664 } else { 0xaa64 } + if ($pe -lt 64 -or $pe -gt $bytes.Length - 24 -or + [BitConverter]::ToUInt32($bytes, $pe) -ne 0x4550 -or + [BitConverter]::ToUInt16($bytes, $pe + 4) -ne $machine) { + throw "Invalid PE architecture for $native (expected $Architecture)" + } +} + +if ($Mode -eq "Write") { + if (Test-Path -LiteralPath $manifestPath) { throw "Artifact manifest already exists: $manifestPath" } + $identity.files = $files + $identity | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $manifestPath -Encoding utf8 +} else { + $manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json -AsHashtable + foreach ($key in $identity.Keys) { + if (-not $manifest.ContainsKey($key) -or $manifest[$key] -cne $identity[$key]) { + throw "Artifact $key mismatch in $manifestPath" + } + } + if ($manifest.files -isnot [System.Collections.IDictionary] -or + @(Compare-Object @($files.Keys | Sort-Object) @($manifest.files.Keys | Sort-Object)).Count) { + throw "Artifact file set mismatch in $manifestPath" + } + foreach ($file in $files.Keys) { + if ($manifest.files[$file] -cne $files[$file]) { throw "Artifact SHA256 mismatch: $file" } + } +} +Write-Host "$Mode verified $Kind $Architecture $Profile $Features ($($files.Count) files, $($identity.commit))" diff --git a/eng/ci/assert-success.ps1 b/eng/ci/assert-success.ps1 new file mode 100644 index 00000000..b45a06ba --- /dev/null +++ b/eng/ci/assert-success.ps1 @@ -0,0 +1,31 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [Parameter(Mandatory)][string]$NeedsJson, + [Parameter(Mandatory)][string[]]$RequiredJobs, + [ValidateSet("true", "false")][string]$DocsOnly = "false", + [string[]]$SkippableJobs = @() +) + +$ErrorActionPreference = "Stop" +$needs = $NeedsJson | ConvertFrom-Json -AsHashtable +if ($needs -isnot [System.Collections.IDictionary] -or $RequiredJobs.Count -eq 0) { + throw "A success gate requires named job results." +} +if (@(Compare-Object @($needs.Keys | Sort-Object) @($RequiredJobs | Sort-Object)).Count) { + throw "Success gate dependencies do not match the required jobs." +} +if ($needs.changes.result -ne "success" -or $needs.changes.outputs.docs_only -cne $DocsOnly) { + throw "A success gate requires successful, matching change classification." +} +if (@($SkippableJobs | Where-Object { $_ -notin $RequiredJobs -or $_ -eq "changes" }).Count) { + throw "Only declared heavy dependencies may be skipped." +} +foreach ($job in $RequiredJobs) { + $expected = if ($DocsOnly -eq "true" -and $job -in $SkippableJobs) { "skipped" } else { "success" } + if ($needs[$job].result -ne $expected) { + throw "Required job '$job' has result '$($needs[$job].result)'; expected '$expected'." + } +} +Write-Host "All required jobs have the expected results (docs-only: $DocsOnly): $($RequiredJobs -join ', ')" diff --git a/eng/ci/classify_changes.py b/eng/ci/classify_changes.py new file mode 100644 index 00000000..e2cf7ffd --- /dev/null +++ b/eng/ci/classify_changes.py @@ -0,0 +1,65 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""PR-only lightweight scheduling for Markdown changes.""" + +import json +import os +from pathlib import Path +import re +import subprocess + + +def documentation_diff(diff: bytes) -> bool: + if not diff: + return False + fields = diff.decode("utf-8").split("\0") + if fields.pop() != "": + raise ValueError("Git name-status output was not NUL-terminated") + index = 0 + while index < len(fields): + status = fields[index] + rename = re.fullmatch(r"R[0-9]{1,3}", status) is not None and int(status[1:]) <= 100 + count = 2 if rename else 1 + paths = fields[index + 1 : index + 1 + count] + if len(paths) != count: + raise ValueError("Incomplete Git name-status record") + if status not in {"A", "M", "D"} and not rename: + return False + if any(not path.lower().endswith(".md") for path in paths): + return False + index += 1 + count + return True + + +def classify(event_name: str, event: dict, repo: Path) -> bool: + if event_name != "pull_request": + return False + pull_request = event["pull_request"] + base, head = (pull_request[side]["sha"] for side in ("base", "head")) + for sha in (base, head): + if not isinstance(sha, str) or not re.fullmatch(r"[0-9a-f]{40}", sha): + raise ValueError("PR base/head must be full Git commit IDs") + merge_base = subprocess.check_output( + ["git", "merge-base", base, head], cwd=repo + ).decode("ascii").strip() + if not re.fullmatch(r"[0-9a-f]{40}", merge_base): + raise ValueError("Git did not resolve a unique PR merge base") + diff = subprocess.check_output( + ["git", "diff", "--name-status", "--find-renames", "-z", merge_base, head, "--"], + cwd=repo, + ) + return documentation_diff(diff) + + +def main() -> None: + event_name = os.environ["GITHUB_EVENT_NAME"] + event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8")) + docs_only = classify(event_name, event, Path.cwd()) + print(f"CI mode: {'documentation-only PR' if docs_only else 'full validation'}") + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write(f"docs_only={str(docs_only).lower()}\n") + + +if __name__ == "__main__": + main() diff --git a/eng/ci/merge-runtime-artifacts.ps1 b/eng/ci/merge-runtime-artifacts.ps1 new file mode 100644 index 00000000..78c61dca --- /dev/null +++ b/eng/ci/merge-runtime-artifacts.ps1 @@ -0,0 +1,26 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [Parameter(Mandatory)][string]$X64, + [Parameter(Mandatory)][string]$Arm64, + [Parameter(Mandatory)][string]$Output +) + +$ErrorActionPreference = "Stop" +& (Join-Path $PSScriptRoot "artifact.ps1") -Mode Verify -Path $X64 -Kind js -Architecture x64 +& (Join-Path $PSScriptRoot "artifact.ps1") -Mode Verify -Path $Arm64 -Kind js -Architecture arm64 +$left = (Get-Content -LiteralPath (Join-Path $X64 "manifest.json") -Raw | ConvertFrom-Json -AsHashtable).files +$right = (Get-Content -LiteralPath (Join-Path $Arm64 "manifest.json") -Raw | ConvertFrom-Json -AsHashtable).files +$sidecars = @($left.Keys | Where-Object { $_ -notlike "*.node" } | Sort-Object) +$otherSidecars = @($right.Keys | Where-Object { $_ -notlike "*.node" } | Sort-Object) +if (@(Compare-Object $sidecars $otherSidecars).Count) { + throw "Runtime architecture artifacts have different sidecar file sets." +} +foreach ($file in $sidecars) { + if ($left[$file] -cne $right[$file]) { throw "Runtime sidecar differs between architectures: $file" } +} +if (Test-Path -LiteralPath $Output) { throw "Runtime assembly output must not already exist: $Output" } +New-Item -ItemType Directory -Path $Output -Force | Out-Null +Copy-Item -Path (Join-Path $X64 "payload\*") -Destination $Output -Recurse +Copy-Item -LiteralPath (Join-Path $Arm64 "payload\dynwinrt.win32-arm64-msvc.node") -Destination $Output diff --git a/eng/ci/requirements.txt b/eng/ci/requirements.txt new file mode 100644 index 00000000..4105ab7d --- /dev/null +++ b/eng/ci/requirements.txt @@ -0,0 +1,2 @@ +PyYAML==6.0.3 +packaging>=24,<27 diff --git a/eng/ci/test_ci.py b/eng/ci/test_ci.py new file mode 100644 index 00000000..eba5666f --- /dev/null +++ b/eng/ci/test_ci.py @@ -0,0 +1,435 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import copy +import json +import os +from pathlib import Path +import shutil +import struct +import subprocess +import tempfile +import unittest + +import yaml + +from classify_changes import classify, documentation_diff + + +ROOT = Path(__file__).resolve().parents[2] +CI = ROOT / "eng" / "ci" +WORKFLOW = yaml.safe_load((ROOT / ".github" / "workflows" / "build.yml").read_text(encoding="utf-8")) +JOBS = WORKFLOW["jobs"] +HEAVY = { + "test-rust", "build-codegen-x64", "build-bindings-x64", "build-js-test-hooks", + "build-arm64", "e2e-runtime", "e2e-native", +} +GATES = {"test", "e2e", "dynwinrt", "dynwinrt-codegen", "ci-success"} + + +def powershell(script, *arguments, env=None): + return subprocess.run( + ["pwsh", "-NoProfile", "-File", str(script), *map(str, arguments)], + cwd=ROOT, env=env, text=True, encoding="utf-8", capture_output=True, + ) + + +class ClassificationTests(unittest.TestCase): + def test_markdown_paths_default_to_lightweight(self): + for path in ( + "README.md", "new/directory/new.md", "docs/guides/new-guide.md", + "samples/new/README.md", "bindings/js/README.md", "bindings/py/README.md", + "tools/dynwinrt-codegen/npm/README.md", "tools/dynwinrt-codegen/python/README.md", + "eng/release/RELEASE_NOTES.md", "docs/status/TODO.md", + "docs/status/generated/classic-com-named-types.md", "docs/status/future-report.md", + "docs/UPPER.MD", "docs/Mixed.mD", "docs/with spaces.md", "docs/with\nnewline.md", + ): + for status in ("A", "M", "D"): + with self.subTest(path=path, status=status): + self.assertTrue(documentation_diff(f"{status}\0{path}\0".encode())) + self.assertTrue(documentation_diff(b"M\0README.md\0A\0future/new.md\0")) + + def test_non_markdown_and_mixed_changes_need_full_validation(self): + for path in ( + "docs/status/generated/classic-com-capability-summary.json", + "docs/status/generated/classic-com-interface-support.csv", + "contracts/schema/contract.schema.json", "tests/e2e/e2e_specs.schema.json", + "eng/ci/classify_changes.py", ".github/workflows/build.yml", + "samples/js/ocr/main.ts", "samples/js/ocr/package.json", "crates/dynwinrt/src/lib.rs", + "future/unknown.data", "docs/guide.markdown", "docs/guide.mdx", "README.md.bak", + "notesmd", "", + ): + with self.subTest(path=path): + self.assertFalse(documentation_diff(f"A\0{path}\0".encode())) + self.assertFalse(documentation_diff(f"M\0README.md\0M\0{path}\0".encode())) + + def test_deletions_renames_unknown_status_and_empty_diff(self): + self.assertTrue(documentation_diff(b"D\0README.md\0")) + self.assertTrue(documentation_diff(b"R100\0README.md\0samples/js/README.md\0")) + self.assertTrue(documentation_diff(b"R075\0old/guide.MD\0new/guide.md\0")) + self.assertFalse(documentation_diff(b"R100\0src/main.rs\0README.md\0")) + self.assertFalse(documentation_diff(b"R100\0README.md\0src/main.rs\0")) + self.assertFalse(documentation_diff(b"D\0src/main.rs\0A\0README.md\0")) + for status in ("T", "U", "X", "C100", "R", "R101", "R1000", "R-1"): + with self.subTest(status=status): + self.assertFalse(documentation_diff(f"{status}\0README.md\0new.md\0".encode())) + self.assertFalse(documentation_diff(b"")) + for malformed in (b"M\0README.md", b"R100\0README.md\0", b"M\0"): + with self.subTest(diff=malformed), self.assertRaises(ValueError): + documentation_diff(malformed) + + def test_entire_pr_history_and_missing_history(self): + with tempfile.TemporaryDirectory(prefix="dynwinrt-ci-git-") as directory: + repo = Path(directory) + + def git(*args): + return subprocess.check_output(["git", *args], cwd=repo).decode().strip() + + git("init", "--quiet") + git("config", "user.name", "CI test") + git("config", "user.email", "ci@example.invalid") + (repo / "README.md").write_text("base\n") + (repo / "code.rs").write_text("base\n") + git("add", ".") + git("commit", "--quiet", "-m", "base") + base = git("rev-parse", "HEAD") + (repo / "code.rs").write_text("changed\n") + git("commit", "--quiet", "-am", "code in earlier PR commit") + (repo / "README.md").write_text("docs in latest commit\n") + git("commit", "--quiet", "-am", "docs") + event = {"pull_request": {"base": {"sha": base}, "head": {"sha": git("rev-parse", "HEAD")}}} + self.assertFalse(classify("pull_request", event, repo)) + # The latest commit alone is docs-only, but the full PR above is not. + event["pull_request"]["base"]["sha"] = git("rev-parse", "HEAD~1") + self.assertTrue(classify("pull_request", event, repo)) + (repo / "new").mkdir() + (repo / "new" / "guide.MD").write_text("new Markdown\n") + git("add", ".") + git("commit", "--quiet", "-m", "new Markdown directory") + event["pull_request"]["head"]["sha"] = git("rev-parse", "HEAD") + self.assertTrue(classify("pull_request", event, repo)) + event["pull_request"]["base"]["sha"] = base + self.assertFalse(classify("pull_request", event, repo)) + self.assertFalse(classify("push", event, repo)) + self.assertFalse(classify("workflow_dispatch", event, repo)) + event["pull_request"]["head"]["sha"] = "f" * 40 + with self.assertRaises(subprocess.CalledProcessError): + classify("pull_request", event, repo) + event["pull_request"]["head"]["sha"] = "--help" + with self.assertRaises(ValueError): + classify("pull_request", event, repo) + + +class PackageSourceTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="dynwinrt-ci-source-") + self.addCleanup(self.temporary.cleanup) + self.repo = Path(self.temporary.name) + for relative in ( + "bindings/py/Cargo.toml", "bindings/py/pyproject.toml", "bindings/py/README.md", + "tools/dynwinrt-codegen/Cargo.toml", "tools/dynwinrt-codegen/pyproject.toml", + "tools/dynwinrt-codegen/python/README.md", + "tools/dynwinrt-codegen/src/codegen/package.rs", + "eng/release/python/verify_python_release.py", + ): + target = self.repo / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / relative, target) + steps = [ + step for step in JOBS["format"]["steps"] + if step.get("name") == "Validate Python package source metadata" + ] + self.assertEqual(len(steps), 1) + self.assertNotIn("if", JOBS["format"]) + self.assertNotIn("if", steps[0]) + self.assertEqual(steps[0]["shell"], "pwsh") + script = self.repo / "step.ps1" + script.write_text( + "$ErrorActionPreference = 'Stop'\n" + + steps[0]["run"] + + "\nif (Test-Path -LiteralPath variable:\\LASTEXITCODE) { exit $LASTEXITCODE }\n", + encoding="utf-8", + ) + quoted_script = str(script).replace("'", "''") + self.command = f". '{quoted_script}'" + + def run_step(self): + return subprocess.run( + ["pwsh", "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", self.command], + cwd=self.repo, text=True, encoding="utf-8", capture_output=True, + ) + + def test_source_step_succeeds_in_github_wrapper(self): + result = self.run_step() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("source metadata OK:", result.stdout) + + def test_metadata_failure_reaches_github_wrapper(self): + manifest = self.repo / "bindings" / "py" / "Cargo.toml" + original = manifest.read_text(encoding="utf-8") + version = next(line for line in original.splitlines() if line.startswith("version = ")) + manifest.write_text(original.replace(version, 'version = "999.0.0"', 1), encoding="utf-8") + result = self.run_step() + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("Runtime and codegen Cargo versions must match", result.stdout + result.stderr) + + def test_missing_empty_and_invalid_readmes_fail_in_github_wrapper(self): + for relative in ("bindings/py/README.md", "tools/dynwinrt-codegen/python/README.md"): + readme = self.repo / relative + original = readme.read_bytes() + for contents in (None, "", "# Unrelated package\n"): + with self.subTest(readme=relative, contents=contents): + try: + if contents is None: + readme.unlink() + else: + readme.write_text(contents, encoding="utf-8") + result = self.run_step() + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("Package README", result.stdout + result.stderr) + finally: + readme.write_bytes(original) + + +class WorkflowTests(unittest.TestCase): + def ancestors(self, job): + needs = JOBS[job].get("needs", []) + if isinstance(needs, str): + needs = [needs] + return set(needs).union(*(self.ancestors(parent) for parent in needs)) + + def test_graph_and_parallel_consumers(self): + self.assertEqual(WORKFLOW["permissions"], {"contents": "read"}) + # PyYAML uses YAML 1.1: an unquoted "on" key is represented by True. + triggers = WORKFLOW.get("on", WORKFLOW.get(True)) + self.assertEqual(set(triggers), {"push", "pull_request"}) + self.assertNotIn("paths-ignore", triggers["pull_request"]) + self.assertEqual(JOBS["changes"]["steps"][0]["with"]["fetch-depth"], 0) + for job in HEAVY: + self.assertEqual(JOBS[job]["if"], "needs.changes.outputs.docs_only == 'false'") + for producer in ("build-codegen-x64", "build-bindings-x64", "build-js-test-hooks", "build-arm64"): + self.assertEqual(set(JOBS[producer]["needs"]), {"format", "changes"}) + for consumer in ("e2e-runtime", "e2e-native"): + self.assertTrue(self.ancestors(consumer).isdisjoint({"test", "test-rust", "build-arm64"})) + for final in ("dynwinrt", "dynwinrt-codegen"): + self.assertTrue({"test", "e2e", "build-arm64"} <= self.ancestors(final)) + self.assertEqual(set(JOBS["ci-success"]["needs"]), set(JOBS) - {"ci-success"}) + + def test_current_run_artifacts_and_no_consumer_rebuilds(self): + uploads = {} + for job, config in JOBS.items(): + for step in config["steps"]: + action = step.get("uses", "") + if action.startswith("actions/upload-artifact@"): + name = step["with"]["name"] + self.assertNotIn(name, uploads) + self.assertEqual(step["with"]["if-no-files-found"], "error") + uploads[name] = job + for job, config in JOBS.items(): + for step in config["steps"]: + if step.get("uses", "").startswith("actions/download-artifact@"): + inputs = step["with"] + self.assertEqual(set(inputs), {"name", "path"}) + producer = uploads[inputs["name"]] + self.assertTrue(producer == job or producer in self.ancestors(job)) + self.assertEqual(uploads["dynwinrt"], "dynwinrt") + self.assertEqual(uploads["dynwinrt-codegen"], "dynwinrt-codegen") + for job in ("e2e-runtime", "e2e-native", "dynwinrt", "dynwinrt-codegen"): + commands = "\n".join(step.get("run", "") for step in JOBS[job]["steps"]) + for forbidden in ("cargo build", "cargo run", "napi build", "maturin build", "npm run test:tsfn", + "npm run test:generated-unsafe", "npm run test:native-completion", + "npm run test:borrowed-copy"): + self.assertNotIn(forbidden, commands) + runtime = "\n".join(step.get("run", "") for step in JOBS["e2e-runtime"]["steps"]) + self.assertIn("cargo test -p dynwinrt-codegen --test implementation_naming_test", runtime) + + def test_release_notes_validated_in_lightweight_lane(self): + steps = [ + step for step in JOBS["format"]["steps"] + if step.get("name") == "Validate checked-in release notes" + ] + self.assertEqual(len(steps), 1) + self.assertNotIn("if", JOBS["format"]) + self.assertNotIn("if", steps[0]) + self.assertEqual(steps[0]["shell"], "pwsh") + self.assertEqual(steps[0]["run"].splitlines(), [ + r".\eng\release\validate_release_notes.ps1", + r".\eng\release\test_validate_release_notes.ps1", + ]) + + def test_gate_truth_tables_execute_the_real_gate(self): + # Run the entire matrix in one PowerShell process, not hundreds of shells. + cases = [] + for job in GATES: + config = JOBS[job] + self.assertEqual(config["if"], "${{ always() }}") + gate_index, gate = next( + (index, step) for index, step in enumerate(config["steps"]) + if "assert-success.ps1" in step.get("run", "") + ) + env = gate["env"] + required = env["REQUIRED_JOBS"].split(",") + skipped = env["DOCS_SKIPPABLE_JOBS"].split(",") + self.assertEqual(set(required), set(config["needs"])) + self.assertEqual(set(skipped), HEAVY & set(required)) + self.assertEqual(env["DOCS_ONLY"], "${{ needs.changes.outputs.docs_only }}") + if job in {"dynwinrt", "dynwinrt-codegen"}: + for step in config["steps"][gate_index + 1:]: + self.assertEqual(step["if"], "needs.changes.outputs.docs_only == 'false'") + for docs in (False, True): + needs = {name: {"result": "skipped" if docs and name in skipped else "success"} for name in required} + needs["changes"]["outputs"] = {"docs_only": str(docs).lower()} + case = {"needs": needs, "required": required, "skipped": skipped, "docs": str(docs).lower(), "ok": True} + cases.append(case) + for dependency in required: + for result in ("success", "failure", "cancelled", "skipped", ""): + if result == needs[dependency]["result"]: + continue + broken = copy.deepcopy(case) + broken["needs"][dependency]["result"] = result + broken["ok"] = False + cases.append(broken) + missing = copy.deepcopy(case) + del missing["needs"][required[-1]] + missing["ok"] = False + cases.append(missing) + unknown = copy.deepcopy(case) + unknown["needs"]["unexpected"] = {"result": "success"} + unknown["ok"] = False + cases.append(unknown) + inconsistent = copy.deepcopy(case) + inconsistent["needs"]["changes"]["outputs"]["docs_only"] = str(not docs).lower() + inconsistent["ok"] = False + cases.append(inconsistent) + with tempfile.TemporaryDirectory(prefix="dynwinrt-ci-gates-") as directory: + cases_path = Path(directory) / "cases.json" + cases_path.write_text(json.dumps(cases)) + harness = Path(directory) / "gates.ps1" + harness.write_text( + 'param([string]$Gate, [string]$Cases)\n' + '$ErrorActionPreference = "Stop"\n' + '$index = 0\n' + 'foreach ($case in (Get-Content $Cases -Raw | ConvertFrom-Json)) {\n' + ' $passed = $true\n' + ' try {\n' + ' & $Gate -NeedsJson ($case.needs | ConvertTo-Json -Depth 5 -Compress) ' + '-RequiredJobs $case.required -DocsOnly $case.docs -SkippableJobs $case.skipped | Out-Null\n' + ' } catch { $passed = $false }\n' + ' if ($passed -ne $case.ok) { throw "Gate truth-table case ${index}: expected $($case.ok)" }\n' + ' $index++\n' + '}\n', + encoding="utf-8", + ) + result = powershell(harness, CI / "assert-success.ps1", cases_path) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +class ArtifactTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="dynwinrt-ci-artifact-") + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.env = {**os.environ, "GITHUB_SHA": "1" * 40, "GITHUB_RUN_ID": "12345"} + + def invoke(self, mode, path, kind="js", arch="x64", *extra, ok=True): + result = powershell( + CI / "artifact.ps1", "-Mode", mode, "-Path", path, "-Kind", kind, + "-Architecture", arch, *extra, env=self.env, + ) + self.assertEqual(result.returncode == 0, ok, result.stdout + result.stderr) + + def payload(self, name, arch="x64", kind="js"): + artifact = self.root / name + payload = artifact / "payload" + payload.mkdir(parents=True) + native = payload / ("dynwinrt-codegen.exe" if kind == "codegen" else f"dynwinrt.win32-{arch}-msvc.node") + image = bytearray(128) + struct.pack_into(" None: ) assert runtime_project["readme"] == README_SPECS["dynwinrt"] assert codegen_project["readme"] == README_SPECS["dynwinrt-codegen"] + for package, directory in ( + ("dynwinrt", ROOT / "bindings" / "py"), + ("dynwinrt-codegen", ROOT / "tools" / "dynwinrt-codegen"), + ): + readme = directory / README_SPECS[package]["file"] + assert readme.is_file(), f"Package README is missing: {readme}" + expected_heading = README_HEADINGS[package] + assert readme.read_text(encoding="utf-8").strip().startswith(expected_heading), ( + f"Package README {readme} must start with {expected_heading!r}" + ) generated_manifest = ( ROOT / "tools" / "dynwinrt-codegen" / "src" / "codegen" / "package.rs" diff --git a/eng/release/test_validate_release_notes.ps1 b/eng/release/test_validate_release_notes.ps1 new file mode 100644 index 00000000..2a872d46 --- /dev/null +++ b/eng/release/test_validate_release_notes.ps1 @@ -0,0 +1,187 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +[CmdletBinding()] +param( + [string]$RepositoryRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$validatorPath = Join-Path $PSScriptRoot "validate_release_notes.ps1" +$pipelinePath = Join-Path $RepositoryRoot ".pipelines/release.yml" +$releaseNotesPath = Join-Path $RepositoryRoot "eng/release/RELEASE_NOTES.md" +$tempRoot = Join-Path ([IO.Path]::GetTempPath()) "dynwinrt-release-notes-$([guid]::NewGuid())" +$tempPipelinePath = Join-Path $tempRoot ".pipelines/release.yml" +$tempNotesPath = Join-Path $tempRoot "eng/release/RELEASE_NOTES.md" +$utf8NoBom = [Text.UTF8Encoding]::new($false) + +function Write-TestFile { + param( + [string]$Path, + [string]$Contents + ) + + [IO.File]::WriteAllText($Path, $Contents, $utf8NoBom) +} + +function Assert-ValidationFails { + param( + [string]$Name, + [string]$Pipeline, + [AllowEmptyString()][string]$Notes, + [bool]$CreateNotes, + [string]$ExpectedMessage + ) + + Write-TestFile -Path $tempPipelinePath -Contents $Pipeline + if ($CreateNotes) { + Write-TestFile -Path $tempNotesPath -Contents $Notes + } else { + Remove-Item -LiteralPath $tempNotesPath -Force -ErrorAction SilentlyContinue + } + + try { + & $validatorPath -RepositoryRoot $tempRoot | Out-Null + throw "Expected validation failure for '$Name'" + } catch { + if ($_.Exception.Message -notlike $ExpectedMessage) { + throw "Unexpected failure for '$Name': $($_.Exception.Message)" + } + } + + Write-Host "Rejected invalid configuration: $Name" +} + +function Assert-ValidationPasses { + param( + [string]$Name, + [string]$Pipeline, + [string]$Notes + ) + + Write-TestFile -Path $tempPipelinePath -Contents $Pipeline + Write-TestFile -Path $tempNotesPath -Contents $Notes + & $validatorPath -RepositoryRoot $tempRoot | Out-Null + Write-Host "Accepted valid configuration: $Name" +} + +& $validatorPath -RepositoryRoot $RepositoryRoot + +$validPipeline = Get-Content -LiteralPath $pipelinePath -Raw +$validNotes = Get-Content -LiteralPath $releaseNotesPath -Raw +$newline = if ($validPipeline.Contains("`r`n")) { "`r`n" } else { "`n" } + +New-Item -ItemType Directory -Force -Path ` + (Split-Path $tempPipelinePath -Parent), ` + (Split-Path $tempNotesPath -Parent) | Out-Null + +try { + $checkoutBlock = " - checkout: self${newline} fetchDepth: 1" + $singleTaskDoubleCheckout = $validPipeline.Replace( + " - task: GitHubRelease@1", + " - task: 'GitHubRelease@1'" + ).Replace( + $checkoutBlock, + " - checkout: `"self`"${newline} fetchDepth: 1" + ) + Assert-ValidationPasses -Name "single-quoted task and double-quoted checkout" ` + -Pipeline $singleTaskDoubleCheckout -Notes $validNotes + + $doubleTaskSingleCheckout = $validPipeline.Replace( + " - task: GitHubRelease@1", + " - task: `"GitHubRelease@1`"" + ).Replace( + $checkoutBlock, + " - checkout: 'self'${newline} fetchDepth: 1" + ) + Assert-ValidationPasses -Name "double-quoted task and single-quoted checkout" ` + -Pipeline $doubleTaskSingleCheckout -Notes $validNotes + + $quotedDuplicateTasks = @( + " - task: 'GitHubRelease@1'" + "" + " - task: `"GitHubRelease@1`"" + ) -join $newline + $duplicateTaskPipeline = $validPipeline.Replace( + " - task: GitHubRelease@1", + $quotedDuplicateTasks + ) + Assert-ValidationFails -Name "quoted duplicate GitHub release task" ` + -Pipeline $duplicateTaskPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "Expected exactly one active GitHubRelease@1 task, found 2" + + $commentedExpectedValues = @( + " releaseNotesSource: 'inline'" + " # releaseNotesSource: 'filePath'" + ' # releaseNotesFilePath: ''$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md''' + " # addChangeLog: true" + ) -join $newline + $commentedPipeline = $validPipeline.Replace( + " releaseNotesSource: 'filePath'", + $commentedExpectedValues + ) + Assert-ValidationFails -Name "expected values only in comments" ` + -Pipeline $commentedPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "*releaseNotesSource*must be 'filePath'*" + + $activeInlinePipeline = $validPipeline.Replace( + " releaseNotesSource: 'filePath'", + " releaseNotesSource: 'inline'" + ) + $unrelatedExpectedValues = @( + " - task: PowerShell@2" + " displayName: Unrelated expected values" + " inputs:" + " targetType: inline" + " script: Write-Host test" + " env:" + " releaseNotesSource: 'filePath'" + ' releaseNotesFilePath: ''$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md''' + " addChangeLog: true" + "" + " - task: GitHubRelease@1" + ) -join $newline + $unrelatedPipeline = $activeInlinePipeline.Replace( + " - task: GitHubRelease@1", + $unrelatedExpectedValues + ) + Assert-ValidationFails -Name "expected values on an unrelated task" ` + -Pipeline $unrelatedPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "*releaseNotesSource*must be 'filePath'*" + + $wrongPathPipeline = $validPipeline.Replace( + 'releaseNotesFilePath: ''$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md''', + 'releaseNotesFilePath: ''$(Build.SourcesDirectory)/eng/release/BROKEN.md''' + ) + Assert-ValidationFails -Name "wrong active release notes path" ` + -Pipeline $wrongPathPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "*releaseNotesFilePath*RELEASE_NOTES.md*BROKEN.md*" + + $disabledChangeLogPipeline = $validPipeline.Replace( + "addChangeLog: true", + "addChangeLog: false" + ) + Assert-ValidationFails -Name "disabled active changelog" ` + -Pipeline $disabledChangeLogPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "*addChangeLog*must be 'true'*" + + $checkoutNoneBlock = " - checkout: none${newline} # - checkout: self${newline} # fetchDepth: 1" + $missingCheckoutPipeline = $validPipeline.Replace($checkoutBlock, $checkoutNoneBlock) + Assert-ValidationFails -Name "release job source checkout unavailable" ` + -Pipeline $missingCheckoutPipeline -Notes $validNotes -CreateNotes $true ` + -ExpectedMessage "*explicitly checkout 'self'*" + + Assert-ValidationFails -Name "empty release notes" ` + -Pipeline $validPipeline -Notes "" -CreateNotes $true ` + -ExpectedMessage "Release notes file is empty:*" + + Assert-ValidationFails -Name "missing release notes" ` + -Pipeline $validPipeline -Notes "" -CreateNotes $false ` + -ExpectedMessage "Release notes file is missing:*" +} finally { + Remove-Item -LiteralPath $tempRoot -Recurse -Force -ErrorAction SilentlyContinue +} + +Write-Host "Release notes validation regression tests passed" diff --git a/eng/release/validate_release_notes.ps1 b/eng/release/validate_release_notes.ps1 new file mode 100644 index 00000000..2e9ce1d9 --- /dev/null +++ b/eng/release/validate_release_notes.ps1 @@ -0,0 +1,238 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +[CmdletBinding()] +param( + [string]$RepositoryRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +function Get-Indent { + param([string]$Line) + + return $Line.Length - $Line.TrimStart().Length +} + +function Get-BlockEnd { + param( + [string[]]$Lines, + [int]$Start, + [int]$Indent + ) + + for ($index = $Start + 1; $index -lt $Lines.Count; $index++) { + $trimmed = $Lines[$index].Trim() + if (-not $trimmed -or $trimmed.StartsWith("#")) { + continue + } + if ((Get-Indent $Lines[$index]) -le $Indent) { + return $index + } + } + + return $Lines.Count +} + +function ConvertFrom-YamlScalar { + param([string]$Value) + + $valueWithoutComment = ($Value -split "\s+#", 2)[0].Trim() + if ($valueWithoutComment -match "^'(?(?:[^']|'')*)'$") { + return $Matches.value.Replace("''", "'") + } + if ($valueWithoutComment -match '^"(?[^"]*)"$') { + return $Matches.value + } + return $valueWithoutComment +} + +function Get-DirectMapping { + param( + [string[]]$Lines, + [int]$Start, + [int]$End, + [int]$ParentIndent + ) + + $mapping = @{} + $entryIndent = $ParentIndent + 2 + for ($index = $Start + 1; $index -lt $End; $index++) { + $trimmed = $Lines[$index].Trim() + if (-not $trimmed -or $trimmed.StartsWith("#")) { + continue + } + if ((Get-Indent $Lines[$index]) -ne $entryIndent) { + continue + } + if ($Lines[$index] -notmatch "^\s*(?[A-Za-z][A-Za-z0-9]*):\s*(?.*?)\s*$") { + continue + } + + $key = $Matches.key + if ($mapping.ContainsKey($key)) { + throw "Duplicate '$key' entry in active YAML mapping" + } + $mapping[$key] = ConvertFrom-YamlScalar $Matches.value + } + + return $mapping +} + +function Assert-TaskInput { + param( + [hashtable]$Inputs, + [string]$Name, + [string]$Expected + ) + + if (-not $Inputs.ContainsKey($Name)) { + throw "GitHubRelease@1 input '$Name' is missing" + } + if ($Inputs[$Name] -cne $Expected) { + throw "GitHubRelease@1 input '$Name' must be '$Expected', got '$($Inputs[$Name])'" + } +} + +$releaseNotesRelativePath = "eng/release/RELEASE_NOTES.md" +$releaseNotesPath = Join-Path $RepositoryRoot $releaseNotesRelativePath +$pipelinePath = Join-Path $RepositoryRoot ".pipelines/release.yml" + +if (-not (Test-Path -LiteralPath $releaseNotesPath -PathType Leaf)) { + throw "Release notes file is missing: $releaseNotesRelativePath" +} + +$releaseNotes = Get-Content -LiteralPath $releaseNotesPath -Raw +if ([string]::IsNullOrWhiteSpace($releaseNotes)) { + throw "Release notes file is empty: $releaseNotesRelativePath" +} + +$lines = @(Get-Content -LiteralPath $pipelinePath) +$yamlScalarPattern = "'(?:[^']|'')*'|`"[^`"]*`"|[^#\s]+" +$taskMatches = @() +for ($index = 0; $index -lt $lines.Count; $index++) { + if ($lines[$index] -match "^(?\s*)-\s+task:\s*(?$yamlScalarPattern)\s*(?:#.*)?$") { + $taskIndent = $Matches.indent.Length + $taskValue = ConvertFrom-YamlScalar $Matches.value + if ($taskValue -cne "GitHubRelease@1") { + continue + } + $taskMatches += [pscustomobject]@{ + Index = $index + Indent = $taskIndent + } + } +} + +if ($taskMatches.Count -ne 1) { + throw "Expected exactly one active GitHubRelease@1 task, found $($taskMatches.Count)" +} + +$taskIndex = $taskMatches[0].Index +$taskIndent = $taskMatches[0].Indent +$taskEnd = Get-BlockEnd -Lines $lines -Start $taskIndex -Indent $taskIndent + +$inputsMatches = @() +for ($index = $taskIndex + 1; $index -lt $taskEnd; $index++) { + if ((Get-Indent $lines[$index]) -eq ($taskIndent + 2) -and + $lines[$index] -match "^\s*inputs:\s*(?:#.*)?$") { + $inputsMatches += $index + } +} +if ($inputsMatches.Count -ne 1) { + throw "Expected exactly one active inputs block for GitHubRelease@1, found $($inputsMatches.Count)" +} + +$inputsIndex = $inputsMatches[0] +$inputsIndent = Get-Indent $lines[$inputsIndex] +$inputsEnd = Get-BlockEnd -Lines $lines -Start $inputsIndex -Indent $inputsIndent +$inputs = Get-DirectMapping -Lines $lines -Start $inputsIndex -End $inputsEnd -ParentIndent $inputsIndent + +Assert-TaskInput -Inputs $inputs -Name "releaseNotesSource" -Expected "filePath" +Assert-TaskInput -Inputs $inputs -Name "releaseNotesFilePath" ` + -Expected '$(Build.SourcesDirectory)/eng/release/RELEASE_NOTES.md' +Assert-TaskInput -Inputs $inputs -Name "addChangeLog" -Expected "true" + +$jobIndex = -1 +$jobIndent = -1 +for ($index = $taskIndex - 1; $index -ge 0; $index--) { + if ($lines[$index] -match "^(?\s*)-\s+job:\s*(?[^#\s]+)\s*(?:#.*)?$" -and + $Matches.indent.Length -lt $taskIndent) { + $jobIndex = $index + $jobIndent = $Matches.indent.Length + break + } +} +if ($jobIndex -lt 0) { + throw "GitHubRelease@1 is not inside an active job" +} + +$jobEnd = Get-BlockEnd -Lines $lines -Start $jobIndex -Indent $jobIndent +if ($taskIndex -ge $jobEnd) { + throw "GitHubRelease@1 is not inside the active job block" +} + +$stepsMatches = @() +$templateContextMatches = @() +for ($index = $jobIndex + 1; $index -lt $jobEnd; $index++) { + if ((Get-Indent $lines[$index]) -ne ($jobIndent + 2)) { + continue + } + if ($lines[$index] -match "^\s*steps:\s*(?:#.*)?$") { + $stepsMatches += $index + } + if ($lines[$index] -match "^\s*templateContext:\s*(?:#.*)?$") { + $templateContextMatches += $index + } +} +if ($stepsMatches.Count -ne 1) { + throw "GitHubRelease@1 job must have exactly one active steps block" +} + +$stepsIndex = $stepsMatches[0] +$stepsIndent = Get-Indent $lines[$stepsIndex] +$stepsEnd = Get-BlockEnd -Lines $lines -Start $stepsIndex -Indent $stepsIndent +if ($taskIndex -le $stepsIndex -or $taskIndex -ge $stepsEnd) { + throw "GitHubRelease@1 must be inside the release job's active steps block" +} +if ($templateContextMatches.Count -ne 1) { + throw "GitHubRelease@1 job must have exactly one active templateContext block" +} + +$templateContextIndex = $templateContextMatches[0] +$templateContextIndent = Get-Indent $lines[$templateContextIndex] +$templateContextEnd = Get-BlockEnd -Lines $lines -Start $templateContextIndex ` + -Indent $templateContextIndent +$templateContext = Get-DirectMapping -Lines $lines -Start $templateContextIndex ` + -End $templateContextEnd -ParentIndent $templateContextIndent +if (-not $templateContext.ContainsKey("type") -or + $templateContext["type"] -cne "releaseJob") { + throw "GitHubRelease@1 job must use templateContext type 'releaseJob'" +} + +$stepIndent = $stepsIndent + 2 +$checkoutMatches = @() +for ($index = $stepsIndex + 1; $index -lt $taskIndex; $index++) { + if ((Get-Indent $lines[$index]) -eq $stepIndent -and + $lines[$index] -match "^\s*-\s+checkout:\s*(?$yamlScalarPattern)\s*(?:#.*)?$") { + $checkoutValue = ConvertFrom-YamlScalar $Matches.value + $checkoutMatches += [pscustomobject]@{ + Index = $index + Value = $checkoutValue + } + } +} +if ($checkoutMatches.Count -ne 1 -or $checkoutMatches[0].Value -cne "self") { + throw "GitHubRelease@1 release job must explicitly checkout 'self' before the task" +} + +$checkoutIndex = $checkoutMatches[0].Index +$checkoutEnd = Get-BlockEnd -Lines $lines -Start $checkoutIndex -Indent $stepIndent +$checkout = Get-DirectMapping -Lines $lines -Start $checkoutIndex -End $checkoutEnd ` + -ParentIndent $stepIndent +if (-not $checkout.ContainsKey("fetchDepth") -or $checkout["fetchDepth"] -cne "1") { + throw "GitHubRelease@1 release job checkout must use fetchDepth '1'" +} + +Write-Host "Release notes configuration is valid: $releaseNotesRelativePath is available from the release job checkout" diff --git a/tests/e2e/codegen.ps1 b/tests/e2e/codegen.ps1 new file mode 100644 index 00000000..4953da1c --- /dev/null +++ b/tests/e2e/codegen.ps1 @@ -0,0 +1,33 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +function Get-CodegenInvocation { + param( + [string]$Codegen, + [string]$CargoProfile = "release", + [string]$CargoTarget + ) + + if (-not $Codegen -and $null -ne $env:DYNWINRT_CODEGEN) { + throw "DYNWINRT_CODEGEN must name a prebuilt dynwinrt-codegen executable." + } + if ($Codegen) { + if (-not (Test-Path -LiteralPath $Codegen -PathType Leaf)) { + throw "Prebuilt dynwinrt-codegen does not exist or is not a file: $Codegen" + } + return @{ + Command = (Resolve-Path -LiteralPath $Codegen).Path + Arguments = [string[]]@() + } + } + return @{ + Command = "cargo" + Arguments = [string[]]@( + "run"; "-p"; "dynwinrt-codegen" + if ($CargoProfile -eq "release") { "--release" } + else { "--profile"; $CargoProfile } + if ($CargoTarget) { "--target"; $CargoTarget } + "--quiet"; "--" + ) + } +} diff --git a/tests/e2e/e2e_preparation.tests.ps1 b/tests/e2e/e2e_preparation.tests.ps1 index d755e264..2144028f 100644 --- a/tests/e2e/e2e_preparation.tests.ps1 +++ b/tests/e2e/e2e_preparation.tests.ps1 @@ -3,29 +3,34 @@ # Licensed under the MIT License. $ErrorActionPreference = "Stop" +# Child failures are deliberate assertions, including when CI enables native errors. +$PSNativeCommandUseErrorActionPreference = $false $root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path $scratch = Join-Path $root "target\e2e-preparation-$PID-$([Guid]::NewGuid().ToString('N'))" $scripts = Join-Path $scratch "tests\e2e" $trace = Join-Path $scratch "trace.json" $venv = Join-Path $scratch "bindings\py\.venv\Scripts\python.exe" $explicit = Join-Path $scratch "explicit-python.exe" +$codegen = Join-Path $scratch "prebuilt-codegen.exe" $standard = Join-Path $scripts "e2e_generated\retained.json" $shell = (Get-Process -Id $PID).Path try { New-Item -ItemType Directory -Path $scripts, (Split-Path $venv), (Split-Path $standard) -Force | Out-Null Copy-Item -LiteralPath (Join-Path $PSScriptRoot "e2e_test.ps1") -Destination $scripts - New-Item -ItemType File -Path $venv, $explicit | Out-Null + Copy-Item -LiteralPath (Join-Path $PSScriptRoot "codegen.ps1") -Destination $scripts + New-Item -ItemType File -Path $venv, $explicit, $codegen | Out-Null Set-Content -LiteralPath $standard -Value '{"retained": true}' -NoNewline # Execute the real entrypoint, intercepting only expensive external work. # Both boundaries deliberately fail: tests cannot mistake a stub runner or # stub build for successful generation/native E2E, and check exit propagation. @' -param([string[]]$Lang, [string]$Python, [string]$CargoProfile, [string]$CargoTarget, [switch]$KeepGenerated) +param([string[]]$Lang, [string]$Python, [string]$CargoProfile, [string]$CargoTarget, [string]$Codegen, [switch]$KeepGenerated) @{ stage = "runner"; languages = @($Lang); python = $Python profile = $CargoProfile; target = $CargoTarget; keep = $KeepGenerated.IsPresent + codegen = $Codegen } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $PSScriptRoot "..\..\trace.json") exit 23 '@ | Set-Content -LiteralPath (Join-Path $scripts "implementation_test.ps1") @@ -39,6 +44,11 @@ function cargo { } function node { throw "Node must not run before the focused runner" } $parameters = Get-Content -LiteralPath $CaseFile -Raw | ConvertFrom-Json -AsHashtable +$env:DYNWINRT_CODEGEN = $null +if ($parameters.ContainsKey("EnvironmentCodegen")) { + $env:DYNWINRT_CODEGEN = $parameters.EnvironmentCodegen + $parameters.Remove("EnvironmentCodegen") +} if ($parameters.ContainsKey("HideGlobalTools")) { $parameters.Remove("HideGlobalTools") Remove-Item Function:\node @@ -92,6 +102,23 @@ exit $LASTEXITCODE Suite = "implementations"; Lang = @("py"); SkipBuild = $true; Python = $explicit } 23 "runner" if ($selected.python -ne $explicit -or $selected.keep) { throw "Explicit -Python did not override the existing venv" } + foreach ($option in @("Codegen", "EnvironmentCodegen")) { + $parameters = @{ Suite = "implementations"; Lang = @("py", "ts"); SkipBuild = $true } + $parameters[$option] = $codegen + $selected = Invoke-PreparationCase $parameters 23 "runner" + if ($selected.codegen -ne $codegen) { throw "Prebuilt codegen was not forwarded through $option" } + } + $selected = Invoke-PreparationCase @{ + Suite = "implementations"; Lang = @("py"); SkipBuild = $true + Codegen = $codegen; EnvironmentCodegen = "$scratch\absent.exe" + } 23 "runner" + if ($selected.codegen -ne $codegen) { throw "Explicit -Codegen did not override the environment" } + Invoke-PreparationCase @{ + Suite = "implementations"; Lang = @("py"); SkipBuild = $true; Codegen = "$scratch\absent.exe" + } 1 "" "Prebuilt dynwinrt-codegen does not exist" + Invoke-PreparationCase @{ + Suite = "implementations"; Lang = @("py"); SkipBuild = $true; Codegen = $scratch + } 1 "" "Prebuilt dynwinrt-codegen does not exist" $selected = Invoke-PreparationCase @{ Suite = "implementations"; Lang = @("ts"); SkipBuild = $true } 23 "runner" diff --git a/tests/e2e/e2e_test.ps1 b/tests/e2e/e2e_test.ps1 index 66effb7f..b02b8318 100644 --- a/tests/e2e/e2e_test.ps1 +++ b/tests/e2e/e2e_test.ps1 @@ -9,6 +9,7 @@ # Usage: # .\tests\e2e\e2e_test.ps1 # Full (build + generate + test) # .\tests\e2e\e2e_test.ps1 -SkipBuild # Skip build step +# .\tests\e2e\e2e_test.ps1 -SkipBuild -Codegen C:\artifacts\dynwinrt-codegen.exe # .\tests\e2e\e2e_test.ps1 -Lang py # Python only # .\tests\e2e\e2e_test.ps1 -Lang ts # TypeScript only # .\tests\e2e\e2e_test.ps1 -Lang com # Classic COM only @@ -21,6 +22,8 @@ param( [switch]$KeepGenerated, [string]$CargoProfile = "release", [string]$CargoTarget, + [ValidateNotNullOrEmpty()] + [string]$Codegen = $env:DYNWINRT_CODEGEN, [string]$Python, [ValidateSet("all", "standard", "implementations")] [string]$Suite = "all", @@ -29,6 +32,11 @@ param( ) $ErrorActionPreference = "Stop" +. (Join-Path $PSScriptRoot "codegen.ps1") +$codegenInvocation = Get-CodegenInvocation -Codegen $Codegen -CargoProfile $CargoProfile -CargoTarget $CargoTarget +$codegenCommand = $codegenInvocation.Command +$codegenArguments = $codegenInvocation.Arguments +$codegenOptions = if ($Codegen) { @{ Codegen = $codegenCommand } } else { @{} } $langWasExplicit = $PSBoundParameters.ContainsKey("Lang") if ($Suite -eq "implementations") { $Lang = @($Lang | Where-Object { $_ -in @("py", "ts") }) @@ -151,8 +159,10 @@ function Invoke-NodeRunner([string]$runnerPath, [string[]]$runnerArguments = @() if (-not $SkipBuild) { Write-Host "`n--- Build ---" -ForegroundColor Yellow - & cargo build -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs - if ($LASTEXITCODE -ne 0) { Write-Error "dynwinrt-codegen build failed"; exit 1 } + if (-not $Codegen) { + & cargo build -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs + if ($LASTEXITCODE -ne 0) { Write-Error "dynwinrt-codegen build failed"; exit 1 } + } if ("py" -in $Lang) { Push-Location (Join-Path $root "bindings\py") @@ -210,7 +220,7 @@ if (-not $SkipBuild) { if ($Suite -eq "implementations") { & (Join-Path $PSScriptRoot "implementation_test.ps1") ` -Lang $Lang -Python $pythonExe -CargoProfile $CargoProfile -CargoTarget $CargoTarget ` - -KeepGenerated:$KeepGenerated + @codegenOptions -KeepGenerated:$KeepGenerated exit $LASTEXITCODE } @@ -246,7 +256,7 @@ function Generate($lang, $outDir) { foreach ($ns in ($byNs.Keys | Sort-Object)) { $classes = ($byNs[$ns] | Select-Object -Unique) -join "," Write-Host " $lang`: $ns [$classes]" - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --namespace $ns ` --class-name $classes ` --lang $codegenLang ` @@ -266,7 +276,7 @@ if ("com" -in $Lang) { $comRuntimeImport = "../../../../../../bindings/js/dist/com-unsafe.js" $winrtRuntimeImport = "../../../../../bindings/js/dist/winrt.js" - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --namespace Windows.Win32.UI.Shell ` --class-name "TaskbarList,IShellLinkW,IDataTransferManagerInterop,FileOperation,FileOpenDialog,IFileDialogEvents" ` @@ -274,7 +284,7 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM Shell generation failed"; exit 1 } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --namespace Windows.Win32.System.Com ` --class-name IPersistFile ` @@ -282,7 +292,7 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM persistence generation failed"; exit 1 } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --namespace Windows.Win32.UI.Shell.PropertiesSystem ` --class-name IPropertyStore ` @@ -290,7 +300,7 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM property store generation failed"; exit 1 } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --namespace Windows.Win32.System.WinRT ` --class-name ISystemMediaTransportControlsInterop ` @@ -298,7 +308,7 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM interop generation failed"; exit 1 } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --namespace Windows.Win32.Graphics.Imaging ` --class-name IWICImagingFactory ` @@ -306,7 +316,7 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM WIC generation failed"; exit 1 } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --namespace Windows.Win32.System.Com ` --class-name IStream ` @@ -314,14 +324,14 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM stream generation failed"; exit 1 } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --class-name "Windows.Win32.System.Com.IDispatch,Windows.Win32.System.Ole.IEnumVARIANT" ` --output $comAutomationDir ` --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM Automation generation failed"; exit 1 } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --namespace Windows.Win32.System.Com ` --class-name "IMalloc,IClassFactory,IErrorInfo" ` @@ -329,7 +339,7 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM infrastructure generation failed"; exit 1 } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --namespace Windows.Win32.System.Ole ` --class-name ICreateErrorInfo ` @@ -337,7 +347,7 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM error-info generation failed"; exit 1 } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --namespace Windows.Win32.System.Ole ` --class-name IDropTarget ` @@ -345,7 +355,7 @@ if ("com" -in $Lang) { --import-name $comRuntimeImport if ($LASTEXITCODE -ne 0) { Write-Error "Classic COM callback generation failed"; exit 1 } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --namespace Windows.Media ` --class-name SystemMediaTransportControls ` --output $comSmtcDir ` @@ -371,7 +381,7 @@ if ("win32" -in $Lang) { "Windows.Win32.System.Pipes", "Windows.Win32.Storage.FileSystem" ) | ForEach-Object { "$_.Apis" } - & cargo run -p dynwinrt-codegen @cargoProfileArgs @cargoTargetArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $win32Winmd ` --class-name ($win32Classes -join ",") ` --output $win32BindingsDir ` @@ -501,7 +511,7 @@ if ($Suite -eq "all" -and ("py" -in $Lang -or "ts" -in $Lang)) { $implementationLangs = @($Lang | Where-Object { $_ -in @("py", "ts") }) & (Join-Path $PSScriptRoot "implementation_test.ps1") ` -Lang $implementationLangs -Python $pythonExe ` - -CargoProfile $CargoProfile -CargoTarget $CargoTarget -KeepGenerated + -CargoProfile $CargoProfile -CargoTarget $CargoTarget @codegenOptions -KeepGenerated if ($LASTEXITCODE -ne 0) { $totalFail++ } else { $totalPass++ } foreach ($l in $implementationLangs) { $resultPath = Join-Path $e2eDir "implementations\results_$l.json" diff --git a/tests/e2e/implementation_test.ps1 b/tests/e2e/implementation_test.ps1 index 0dca828a..7af2fbe8 100644 --- a/tests/e2e/implementation_test.ps1 +++ b/tests/e2e/implementation_test.ps1 @@ -12,21 +12,22 @@ param( [string]$Python = "python", [string]$CargoProfile = "release", [string]$CargoTarget, + [ValidateNotNullOrEmpty()] + [string]$Codegen = $env:DYNWINRT_CODEGEN, [switch]$KeepGenerated ) $ErrorActionPreference = "Stop" +. (Join-Path $PSScriptRoot "codegen.ps1") +$codegenInvocation = Get-CodegenInvocation -Codegen $Codegen -CargoProfile $CargoProfile -CargoTarget $CargoTarget +$codegenCommand = $codegenInvocation.Command +$codegenArguments = $codegenInvocation.Arguments $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent $out = Join-Path $PSScriptRoot "e2e_generated\implementations" $runtime = Join-Path $root "bindings\js\dist\winrt.js" $failed = 0 $generationResults = @{} $typecheckResults = @{} -[string[]]$cargoArgs = @( - if ($CargoProfile -eq "release") { "--release" } - else { "--profile"; $CargoProfile } - if ($CargoTarget) { "--target"; $CargoTarget } -) $winmd = if ($env:DYNWINRT_WINDOWS_WINMD) { $env:DYNWINRT_WINDOWS_WINMD } else { @@ -65,7 +66,7 @@ foreach ($language in $Lang) { $codegenLanguage = if ($language -eq "py") { "py" } else { "js" } $runtimeImport = [IO.Path]::GetRelativePath($directory, $runtime).Replace("\", "/") $generatedModules = 0 - & cargo run -p dynwinrt-codegen @cargoArgs --quiet -- generate ` + & $codegenCommand @codegenArguments generate ` --winmd $winmd --class-name $classes --lang $codegenLanguage ` --output $directory --import-name $runtimeImport | ForEach-Object { diff --git a/tests/e2e/prebuilt_codegen.tests.ps1 b/tests/e2e/prebuilt_codegen.tests.ps1 new file mode 100644 index 00000000..74e7e17e --- /dev/null +++ b/tests/e2e/prebuilt_codegen.tests.ps1 @@ -0,0 +1,114 @@ +#!/usr/bin/env pwsh +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +$ErrorActionPreference = "Stop" +# Capture the intentional nonzero generation boundaries before checking them. +$PSNativeCommandUseErrorActionPreference = $false +$root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +$scratch = Join-Path $root "target\prebuilt-codegen-$PID-$([Guid]::NewGuid().ToString('N'))" +$scripts = Join-Path $scratch "tests\e2e" +$shell = (Get-Process -Id $PID).Path +$trace = Join-Path $scratch "trace.jsonl" +$prebuilt = Join-Path $scratch "artifact with spaces\codegen.ps1" +$python = Join-Path $scratch "python.ps1" +try { + New-Item -ItemType Directory -Path $scripts, (Split-Path $prebuilt) -Force | Out-Null + foreach ($file in @("e2e_test.ps1", "implementation_test.ps1", "codegen.ps1", "e2e_specs.json")) { + Copy-Item -LiteralPath (Join-Path $PSScriptRoot $file) -Destination $scripts + } + Set-Content -LiteralPath (Join-Path $scratch "metadata.winmd") -Value "external metadata boundary" + Set-Content -LiteralPath $python -Value '$global:LASTEXITCODE = 0' + @' +@{ kind = "prebuilt"; arguments = @($args) } | ConvertTo-Json -Compress | + Add-Content -LiteralPath $env:CODEGEN_TRACE +$outputIndex = [Array]::IndexOf($args, "--output") +if ($outputIndex -ge 0) { New-Item -ItemType Directory -Path $args[$outputIndex + 1] -Force | Out-Null } +$global:LASTEXITCODE = if (@(Get-Content $env:CODEGEN_TRACE).Count -eq [int]$env:CODEGEN_STOP) { 23 } else { 0 } +'@ | Set-Content -LiteralPath $prebuilt + @' +param([string]$CaseFile) +$ErrorActionPreference = "Stop" +function cargo { + @{ kind = "cargo"; arguments = @($args) } | ConvertTo-Json -Compress | Add-Content $env:CODEGEN_TRACE + $global:LASTEXITCODE = 31 +} +$case = Get-Content -LiteralPath $CaseFile -Raw | ConvertFrom-Json -AsHashtable +$env:DYNWINRT_CODEGEN = $case.environmentCodegen +$env:DYNWINRT_WIN32_WINMD = Join-Path $PSScriptRoot "metadata.winmd" +$env:DYNWINRT_WINDOWS_WINMD = $env:DYNWINRT_WIN32_WINMD +$env:CODEGEN_TRACE = Join-Path $PSScriptRoot "trace.jsonl" +$env:CODEGEN_STOP = $case.stop +$parameters = $case.parameters +& (Join-Path $PSScriptRoot "tests\e2e\$($case.script)") @parameters +exit $LASTEXITCODE +'@ | Set-Content -LiteralPath (Join-Path $scratch "harness.ps1") + + function Invoke-GenerationCase([string]$Script, [hashtable]$Parameters, [int]$Stop, [string]$EnvironmentCodegen = "") { + if (Test-Path $trace) { Remove-Item -LiteralPath $trace } + $caseFile = Join-Path $scratch "case.json" + @{ + script = $Script; parameters = $Parameters; stop = $Stop + environmentCodegen = if ($EnvironmentCodegen) { $EnvironmentCodegen } else { $null } + } | + ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $caseFile + $output = & $shell -NoProfile -File (Join-Path $scratch "harness.ps1") $caseFile 2>&1 | Out-String + if ($LASTEXITCODE -eq 0) { throw "The deliberately failing generation boundary became green: $output" } + $records = @(Get-Content -LiteralPath $trace | ForEach-Object { $_ | ConvertFrom-Json }) + if ($records.Count -ne $Stop) { throw "Expected $Stop invocations, got $($records.Count): $output" } + return $records + } + + $active = (Get-Content (Join-Path $scripts "e2e_specs.json") -Raw | ConvertFrom-Json).specs | + Where-Object { -not $_.skip_reason } + $namespaces = @( + foreach ($lang in @("py", "ts")) { + $active | Where-Object { -not $_.langs -or $lang -in $_.langs } | + Select-Object -ExpandProperty namespace -Unique + } + ) + $winrt = Invoke-GenerationCase "e2e_test.ps1" @{ + SkipBuild = $true; Suite = "standard"; Lang = @("py", "ts"); Python = $shell; Codegen = $prebuilt + } $namespaces.Count + $native = Invoke-GenerationCase "e2e_test.ps1" @{ + SkipBuild = $true; Suite = "standard"; Lang = @("com", "win32"); Python = $shell + } 12 $prebuilt + foreach ($record in @($winrt) + @($native)) { + if ($record.kind -ne "prebuilt" -or $record.arguments[0] -ne "generate") { + throw "Artifact mode invoked Cargo or lost generation arguments" + } + } + if ("Windows.Media" -notin @($native | ForEach-Object { + $index = [Array]::IndexOf($_.arguments, "--namespace") + if ($index -ge 0) { $_.arguments[$index + 1] } + })) { throw "COM interop lost WinRT generation" } + if (($native[-1].arguments -join " ") -notlike "*Windows.Win32.System.Registry.Apis*") { + throw "Flat Win32 generation did not use the prebuilt path" + } + foreach ($language in @("py", "ts")) { + $implementation = Invoke-GenerationCase "implementation_test.ps1" @{ + Lang = @($language); Codegen = $prebuilt + } 1 + if ($implementation.kind -ne "prebuilt") { throw "Implementation generation rebuilt codegen" } + } + $pythonNamespaces = @($active | Where-Object { -not $_.langs -or "py" -in $_.langs } | + Select-Object -ExpandProperty namespace -Unique) + $all = Invoke-GenerationCase "e2e_test.ps1" @{ + SkipBuild = $true; Suite = "all"; Lang = @("py"); Python = $python; Codegen = $prebuilt + } ($pythonNamespaces.Count + 1) + if ($all[-1].kind -ne "prebuilt" -or ($all[-1].arguments -join " ") -notlike "*IBackgroundTask*") { + throw "The full suite did not forward prebuilt codegen into its implementation sub-suite" + } + $fallback = Invoke-GenerationCase "e2e_test.ps1" @{ + SkipBuild = $true; Suite = "standard"; Lang = @("py"); Python = $shell + CargoProfile = "coverage"; CargoTarget = "x86_64-pc-windows-msvc" + } 1 + if ($fallback.kind -ne "cargo" -or ($fallback.arguments -join " ") -notlike + "run -p dynwinrt-codegen --profile coverage --target x86_64-pc-windows-msvc --quiet -- generate *") { + throw "Omitted prebuilt override changed the developer/profile fallback" + } + Write-Host "Prebuilt WinRT/COM/Win32/implementation generation and Cargo fallback regressions passed." +} finally { + if (Test-Path -LiteralPath $scratch) { Remove-Item -LiteralPath $scratch -Recurse -Force } +} +exit 0