From 6c11e7103ac4f9bc09717ed690f2e464c923ba28 Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:54:46 +0800 Subject: [PATCH 01/12] ci: reuse each native build's output until its inputs change A 20-line TypeScript change ran every native build for hours. Each native job now restores its finished output from .github/actions/native-cache and skips its build on a hit, so a change rebuilds only the jobs that depend on it: a crate change rebuilds every platform that links the crate, a Windows script change only the Windows jobs, and a TypeScript change nothing. tools/scripts/native-inputs.py computes each output's key from git objects at the commit. A key covers every tracked file except those OWNERS gives only to other outputs, the crates outside the output's cargo closure, other jobs' workflow blocks and the actions its jobs do not use, so an unplaced file rebuilds everything rather than nothing. The week is part of the key, and the release builds with fresh: true. The Apple xcframeworks, built in per-platform jobs, are looked up first, so a hit skips those jobs, as the canvas-svg lookup already did; the restore takes the lookup's key. Keys replace the hand-kept hashFiles lists. tools/tests/check-native-inputs.py, run by Static Checks, fails when a job reads a file its key leaves out: it follows the jobs' steps, scripts and make -n output, and scans every text file in the key (CMake, Gradle, Xcode, Rust, scripts) for paths that lead out of it. It also checks that every cached job skips its build on a hit and reads no value that changes between runs. The npm prerelease job waits for it. --- .github/actions/native-cache/action.yml | 83 ++ .github/workflows/build-native.yml | 238 +++--- .github/workflows/npm_release.yml | 30 +- .github/workflows/pull-request.yml | 23 +- tools/scripts/native-inputs.py | 523 +++++++++++++ tools/tests/check-native-inputs.py | 985 ++++++++++++++++++++++++ tools/tests/test_native_inputs.py | 389 ++++++++++ 7 files changed, 2177 insertions(+), 94 deletions(-) create mode 100644 .github/actions/native-cache/action.yml create mode 100644 tools/scripts/native-inputs.py create mode 100644 tools/tests/check-native-inputs.py create mode 100644 tools/tests/test_native_inputs.py diff --git a/.github/actions/native-cache/action.yml b/.github/actions/native-cache/action.yml new file mode 100644 index 000000000..7f0c3caa7 --- /dev/null +++ b/.github/actions/native-cache/action.yml @@ -0,0 +1,83 @@ +name: Native output cache +description: > + Restores a job's finished output when nothing it is built from has changed, so the job can skip + its build (every later step is guarded by `if: steps.native.outputs.hit != 'true'`). The key is + the week plus the hash tools/scripts/native-inputs.py computes; its docstring says what that + covers and why. On a miss the job builds, and the output is saved once the job succeeds, into the + scope of the ref that ran it, so pull requests can restore master's entries. With + NATIVE_CACHE_FRESH=true (the release) it neither restores nor saves, and the job builds. + + An output built by several jobs is looked up first, in a job of its own (`lookup-only`), whose + `hit` skips the jobs that build its parts and whose `key` the job that restores it passes back, + so both use the same week. + +inputs: + artifact: + description: The job's entry in tools/scripts/native-inputs.py + required: true + path: + description: The finished output, the same path the job uploads + required: true + variant: + description: "In a matrix job, `${{ toJSON(matrix) }}`: every leg gets its own key" + required: false + default: '' + lookup-only: + description: "'true' to only tell whether the output is cached, without restoring or saving it" + required: false + default: 'false' + key: + description: The key a lookup job computed for this output in the same run + required: false + default: '' + +outputs: + hit: + description: "'true' when the output is cached (and, unless lookup-only, restored), so the build can be skipped" + value: ${{ steps.cache.outputs.cache-hit || steps.lookup.outputs.cache-hit }} + key: + description: The key, for the job that restores the output after a lookup + value: ${{ inputs.key || steps.key.outputs.key }} + +runs: + using: composite + steps: + - name: Inputs + id: key + if: env.NATIVE_CACHE_FRESH != 'true' && inputs.key == '' + shell: bash + env: + ARTIFACT: ${{ inputs.artifact }} + VARIANT: ${{ inputs.variant }} + # --verbose logs the inputs it hashed, to see why a job missed. Windows runners name it + # `python`. The week bounds how old a reused output can be: crates.io versions and toolchains + # float, and each week's first run of an entry rebuilds it. + run: | + py=python3 + "$py" -c '' 2> /dev/null || py=python + hash=$("$py" tools/scripts/native-inputs.py --verbose --job "$GITHUB_JOB" --variant "$VARIANT" "$ARTIFACT") + leg="" + if [ -n "$VARIANT" ] && [ "$VARIANT" != null ]; then + leg=-$(printf '%s' "$VARIANT" | git hash-object --stdin | cut -c1-12) + fi + week=$(date -u +%G-W%V) + # bump the version to drop every entry + echo "key=native-v1-$week-$ARTIFACT$leg-$hash" >> "$GITHUB_OUTPUT" + + # Exact keys only: an output built from other inputs is never the right one. + - name: Restore + id: cache + if: env.NATIVE_CACHE_FRESH != 'true' && inputs.lookup-only != 'true' + uses: actions/cache@v4 + with: + path: ${{ inputs.path }} + key: ${{ inputs.key || steps.key.outputs.key }} + + - name: Look up + id: lookup + if: env.NATIVE_CACHE_FRESH != 'true' && inputs.lookup-only == 'true' + uses: actions/cache/restore@v4 + with: + path: ${{ inputs.path }} + key: ${{ steps.key.outputs.key }} + lookup-only: true diff --git a/.github/workflows/build-native.yml b/.github/workflows/build-native.yml index 15255e57d..02db29cd1 100644 --- a/.github/workflows/build-native.yml +++ b/.github/workflows/build-native.yml @@ -42,10 +42,14 @@ # run the Node-API test suites on the shipped modules (on WARP: runners have no GPU; # audio renders offline and on the 'none' sink: they have no audio device either). # -# The napi-windows modules and the canvas-svg / audio-context mobile builds change rarely, so -# their jobs cache the final artifact keyed on a hash of their sources and skip the whole build -# on a hit. The other jobs that build Skia keep its built libraries per target in -# .github/actions/skia-cache, saved only by pushes to master. +# Every job first restores its finished output from .github/actions/native-cache, keyed on what it +# is built from (tools/scripts/native-inputs.py says what that covers). On a hit it skips its build +# and uploads the restored output, so a change rebuilds only the jobs that depend on it: a crate +# change rebuilds every platform that links the crate, a Windows script change only the Windows +# jobs, and a TypeScript change nothing. An output built by several jobs (the Apple xcframeworks) +# is looked up first, so a hit skips the jobs that build its parts. A job that builds Skia also +# keeps Skia's built libraries per target in .github/actions/skia-cache, saved only by pushes to +# master. name: Build Native permissions: @@ -53,10 +57,15 @@ permissions: on: workflow_call: + inputs: + fresh: + description: Rebuild every output instead of restoring it from .github/actions/native-cache (Skia's prebuilt cache still applies) + type: boolean + default: false env: - # bump to invalidate the canvas-svg / audio-context / canvas-media artifact caches - NATIVE_CACHE_VERSION: v1 + # Read by .github/actions/native-cache. + NATIVE_CACHE_FRESH: ${{ inputs.fresh }} jobs: canvas-android: @@ -64,25 +73,38 @@ jobs: runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 + - uses: ./.github/actions/native-cache + id: native + with: + artifact: canvas-android + path: packages/canvas/platforms/android/canvas-release.aar - uses: ./.github/actions/setup-android-native + if: steps.native.outputs.hit != 'true' - uses: ./.github/actions/skia-cache + if: steps.native.outputs.hit != 'true' with: name: canvas-android - name: Fetch V8 + NativeScript runtime headers + if: steps.native.outputs.hit != 'true' run: ./tools/scripts/download-v8.sh - name: Build libNativeScript.so stub for linking + if: steps.native.outputs.hit != 'true' run: ./tools/scripts/build-android-v8-stub.sh - name: Build Rust libraries + if: steps.native.outputs.hit != 'true' run: make android # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache + if: steps.native.outputs.hit != 'true' with: name: canvas-android save: 'true' - name: Build canvas AAR + if: steps.native.outputs.hit != 'true' working-directory: packages/canvas/src-native/canvas-android run: ./gradlew :canvas:assembleRelease - name: Copy AAR into platforms/android + if: steps.native.outputs.hit != 'true' run: cp packages/canvas/src-native/canvas-android/canvas/build/outputs/aar/canvas-release.aar packages/canvas/platforms/android/canvas-release.aar - uses: actions/upload-artifact@v4 with: @@ -90,10 +112,29 @@ jobs: path: packages/canvas/platforms/android/canvas-release.aar if-no-files-found: error + # A hit for the xcframework skips the per-platform jobs. The lookup runs on macOS, as the restore + # does, so both get the same cache version. + canvas-ios-cache: + name: Canvas xcframework cache lookup + runs-on: macos-15 + outputs: + hit: ${{ steps.native.outputs.hit }} + key: ${{ steps.native.outputs.key }} + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/native-cache + id: native + with: + artifact: canvas-ios + path: canvas-ios.tar.gz + lookup-only: 'true' + # One runner per platform: its Rust targets, then its framework slices. The Xcode pre-build # phase reruns cargo for each slice, so the slices are built in the job that owns the target dir. canvas-apple: name: Canvas ${{ matrix.platform }} + needs: canvas-ios-cache + if: needs.canvas-ios-cache.outputs.hit != 'true' runs-on: macos-15 strategy: fail-fast: false @@ -130,26 +171,38 @@ jobs: canvas-ios: name: Canvas xcframework - needs: canvas-apple + needs: [canvas-ios-cache, canvas-apple] + if: ${{ !cancelled() && needs.canvas-ios-cache.result == 'success' && contains(fromJSON('["success","skipped"]'), needs.canvas-apple.result) }} runs-on: macos-15 steps: - uses: actions/checkout@v4 + - uses: ./.github/actions/native-cache + id: native + with: + artifact: canvas-ios + path: canvas-ios.tar.gz + key: ${{ needs.canvas-ios-cache.outputs.key }} - uses: maxim-lobanov/setup-xcode@v1 + if: steps.native.outputs.hit != 'true' with: xcode-version: '^16.0' - uses: actions/download-artifact@v4 + if: steps.native.outputs.hit != 'true' with: pattern: canvas-apple-* merge-multiple: true path: slices - name: Unpack slices + if: steps.native.outputs.hit != 'true' run: | mkdir -p packages/canvas/src-native/canvas-ios/dist for f in slices/*.tar.gz; do tar -xzf "$f" -C packages/canvas/src-native/canvas-ios/dist; done - name: Build CanvasNative.xcframework + if: steps.native.outputs.hit != 'true' working-directory: tools/scripts run: sh canvas-build.sh --xcframework - name: Pack xcframework + if: steps.native.outputs.hit != 'true' run: tar -czf canvas-ios.tar.gz -C packages/canvas/platforms/ios/CanvasNativeBinary CanvasNative.xcframework - uses: actions/upload-artifact@v4 with: @@ -162,43 +215,42 @@ jobs: runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 - - name: Restore cached AAR - id: svg-aar - uses: actions/cache@v4 + - uses: ./.github/actions/native-cache + id: native with: + artifact: canvas-svg-android path: packages/canvas-svg/platforms/android/canvassvg-release.aar - key: ${{ env.NATIVE_CACHE_VERSION }}-canvas-svg-android-${{ hashFiles('crates/canvas-svg/**', 'crates/canvas-svg-c/**', 'crates/canvas-svg-android/**', 'crates/canvas-utils/**', 'crates/canvas-core/**', 'crates/gl-bindings/**', 'packages/canvas-svg/src-native/android/**', '!packages/canvas-svg/src-native/android/**/build/**', '!packages/canvas-svg/src-native/android/**/jniLibs/**', 'Cargo.lock', 'tools/scripts/build-svg-android.sh', 'tools/scripts/copy-svg-android.sh', 'Makefile') }} - uses: ./.github/actions/setup-android-native - if: steps.svg-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' - uses: ./.github/actions/skia-cache - if: steps.svg-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' with: name: canvas-svg-android # canvassvg's CMake borrows both from packages/canvas (see its CMakeLists.txt) - name: Fetch V8 + NativeScript runtime headers - if: steps.svg-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' run: ./tools/scripts/download-v8.sh - name: Build libNativeScript.so stub for linking - if: steps.svg-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' run: ./tools/scripts/build-android-v8-stub.sh - name: Build Rust libraries - if: steps.svg-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' run: make android-svg # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache - if: steps.svg-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' with: name: canvas-svg-android save: 'true' - name: Copy .so files into jniLibs - if: steps.svg-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' run: sh tools/scripts/copy-svg-android.sh - name: Build canvassvg AAR - if: steps.svg-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' working-directory: packages/canvas-svg/src-native/android run: ./gradlew :canvassvg:assembleRelease - name: Copy AAR into platforms/android - if: steps.svg-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' run: cp packages/canvas-svg/src-native/android/canvassvg/build/outputs/aar/canvassvg-release.aar packages/canvas-svg/platforms/android/canvassvg-release.aar - uses: actions/upload-artifact@v4 with: @@ -206,29 +258,26 @@ jobs: path: packages/canvas-svg/platforms/android/canvassvg-release.aar if-no-files-found: error - # canvas-svg changes rarely: on a hit for its xcframework the per-platform jobs never start. - # The lookup runs on macOS like the restore, so both compute the same cache version. - canvas-svg-cache: - name: Canvas SVG cache lookup + # As canvas-ios: a hit for the xcframework skips the per-platform jobs. + canvas-svg-ios-cache: + name: Canvas SVG xcframework cache lookup runs-on: macos-15 outputs: - key: ${{ steps.key.outputs.key }} - hit: ${{ steps.lookup.outputs.cache-hit }} + hit: ${{ steps.native.outputs.hit }} + key: ${{ steps.native.outputs.key }} steps: - uses: actions/checkout@v4 - - id: key - run: echo "key=${{ env.NATIVE_CACHE_VERSION }}-canvas-svg-ios-${{ hashFiles('crates/canvas-svg/**', 'crates/canvas-svg-c/**', 'crates/canvas-svg-ios/**', 'crates/canvas-utils/**', 'crates/canvas-core/**', 'packages/canvas-svg/src-native/ios/**', '!packages/canvas-svg/src-native/ios/dist/**', 'Cargo.lock', 'tools/scripts/canvas-svg-build.sh', 'Makefile') }}" >> "$GITHUB_OUTPUT" - - id: lookup - uses: actions/cache/restore@v4 + - uses: ./.github/actions/native-cache + id: native with: + artifact: canvas-svg-ios path: canvas-svg-ios.tar.gz - key: ${{ steps.key.outputs.key }} - lookup-only: true + lookup-only: 'true' canvas-svg-apple: name: Canvas SVG ${{ matrix.platform }} - needs: canvas-svg-cache - if: needs.canvas-svg-cache.outputs.hit != 'true' + needs: canvas-svg-ios-cache + if: needs.canvas-svg-ios-cache.outputs.hit != 'true' runs-on: macos-15 strategy: fail-fast: false @@ -262,38 +311,38 @@ jobs: canvas-svg-ios: name: Canvas SVG xcframework - needs: [canvas-svg-cache, canvas-svg-apple] - if: ${{ !cancelled() && needs.canvas-svg-cache.result == 'success' && contains(fromJSON('["success","skipped"]'), needs.canvas-svg-apple.result) }} + needs: [canvas-svg-ios-cache, canvas-svg-apple] + if: ${{ !cancelled() && needs.canvas-svg-ios-cache.result == 'success' && contains(fromJSON('["success","skipped"]'), needs.canvas-svg-apple.result) }} runs-on: macos-15 steps: - uses: actions/checkout@v4 - - name: Restore cached xcframework - id: svg-xcframework - uses: actions/cache@v4 + - uses: ./.github/actions/native-cache + id: native with: + artifact: canvas-svg-ios path: canvas-svg-ios.tar.gz - key: ${{ needs.canvas-svg-cache.outputs.key }} + key: ${{ needs.canvas-svg-ios-cache.outputs.key }} - uses: maxim-lobanov/setup-xcode@v1 - if: steps.svg-xcframework.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' with: xcode-version: '^16.0' - uses: actions/download-artifact@v4 - if: steps.svg-xcframework.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' with: pattern: canvas-svg-apple-* merge-multiple: true path: slices - name: Unpack slices - if: steps.svg-xcframework.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' run: | mkdir -p packages/canvas-svg/src-native/ios/dist for f in slices/*.tar.gz; do tar -xzf "$f" -C packages/canvas-svg/src-native/ios/dist; done - name: Build CanvasSVG.xcframework - if: steps.svg-xcframework.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' working-directory: tools/scripts run: sh canvas-svg-build.sh --xcframework - name: Pack xcframework - if: steps.svg-xcframework.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' run: tar -czf canvas-svg-ios.tar.gz -C packages/canvas-svg/platforms/ios/CanvasSVGBinary CanvasSVG.xcframework - uses: actions/upload-artifact@v4 with: @@ -309,29 +358,28 @@ jobs: with: # Oboe submodules: true - - name: Restore cached AAR - id: audio-aar - uses: actions/cache@v4 + - uses: ./.github/actions/native-cache + id: native with: + artifact: audio-context-android path: packages/audio-context/platforms/android/audiocontext-release.aar - key: ${{ env.NATIVE_CACHE_VERSION }}-audio-context-android-${{ hashFiles('packages/audio-context/src-native/android/**', '!packages/audio-context/src-native/android/**/build/**') }} - uses: actions/setup-java@v4 - if: steps.audio-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' with: distribution: temurin java-version: '17' # read-only off master, see setup-android-native - uses: gradle/actions/setup-gradle@v4 - if: steps.audio-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' - name: Setup Android SDK - if: steps.audio-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' uses: android-actions/setup-android@v4 - name: Build audiocontext AAR - if: steps.audio-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' working-directory: packages/audio-context/src-native/android run: ./gradlew :audiocontext:assembleRelease - name: Copy AAR into platforms/android - if: steps.audio-aar.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' run: cp packages/audio-context/src-native/android/audiocontext/build/outputs/aar/audiocontext-release.aar packages/audio-context/platforms/android/audiocontext-release.aar - uses: actions/upload-artifact@v4 with: @@ -342,29 +390,32 @@ jobs: audio-context-ios: name: AudioContext iOS + visionOS + tvOS + Catalyst runs-on: macos-15 + env: + # Bump to rebuild the opus deps. Kept in this job so the bump also misses the job's + # native-cache entry, which keys on the job's own definition. + OPUS_DEPS_CACHE_VERSION: v1 steps: - uses: actions/checkout@v4 - - name: Restore cached xcframework - id: audio-xcframework - uses: actions/cache@v4 + - uses: ./.github/actions/native-cache + id: native with: + artifact: audio-context-ios path: audio-context-ios.tar.gz - key: ${{ env.NATIVE_CACHE_VERSION }}-audio-context-ios-${{ hashFiles('packages/audio-context/src-native/ios/**', 'tools/scripts/audio-context-build.sh') }} - uses: ./.github/actions/setup-apple-native - if: steps.audio-xcframework.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' with: install-rust: 'false' # libogg / libvorbis / libopus / libopusfile static libs per slice: gitignored, built from # the xiph release tarballs. - name: Restore cached opus deps - if: steps.audio-xcframework.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' id: opus-deps uses: actions/cache@v4 with: path: packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/third_party/build - key: ${{ env.NATIVE_CACHE_VERSION }}-audio-context-opus-deps-${{ hashFiles('packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/fetch_opus_deps.sh', 'packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/build_opus_deps_ios.sh') }} + key: ${{ env.OPUS_DEPS_CACHE_VERSION }}-audio-context-opus-deps-${{ hashFiles('packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/fetch_opus_deps.sh', 'packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/build_opus_deps_ios.sh') }} - name: Build opus deps - if: steps.audio-xcframework.outputs.cache-hit != 'true' && steps.opus-deps.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' && steps.opus-deps.outputs.cache-hit != 'true' working-directory: packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative run: | # opusfile's configure finds the ogg and opus it builds against through pkg-config @@ -372,11 +423,11 @@ jobs: ./scripts/build_opus_deps_ios.sh # same as `npm run build.audiocontext.ios.framework.release` - name: Build AudioContextNative.xcframework - if: steps.audio-xcframework.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' working-directory: tools/scripts run: sh audio-context-build.sh - name: Pack xcframework - if: steps.audio-xcframework.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' run: tar -czf audio-context-ios.tar.gz -C packages/audio-context/platforms/ios/AudioContextNativeBinary AudioContextNative.xcframework - uses: actions/upload-artifact@v4 with: @@ -400,26 +451,37 @@ jobs: shell: bash steps: - uses: actions/checkout@v4 + - uses: ./.github/actions/native-cache + id: native + with: + artifact: canvas-windows + variant: ${{ toJSON(matrix) }} + path: packages/canvas/platforms/windows/${{ matrix.arch }}/ - uses: ./.github/actions/setup-windows-native + if: steps.native.outputs.hit != 'true' with: target: ${{ matrix.target }} - uses: ./.github/actions/skia-cache + if: steps.native.outputs.hit != 'true' with: name: canvas-windows-${{ matrix.arch }} - uses: actions/setup-node@v4 + if: steps.native.outputs.hit != 'true' with: node-version: '22' - name: Build canvasnative.node (and fetch ANGLE) + if: steps.native.outputs.hit != 'true' run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi # arm64 is cross-compiled, so only x64 runs them. The runners have no GPU: D3D12 and ANGLE # fall back to WARP, and the WebGPU suites skip without an adapter. # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache + if: steps.native.outputs.hit != 'true' with: name: canvas-windows-${{ matrix.arch }} save: 'true' - name: Node-API tests - if: matrix.arch == 'x64' + if: steps.native.outputs.hit != 'true' && matrix.arch == 'x64' env: CANVAS_NAPI_ADDON: ${{ github.workspace }}\packages\canvas\platforms\windows\x64\canvasnative.node run: node --expose-gc --test "crates/canvas-napi/__test__/*.test.mjs" @@ -437,29 +499,25 @@ jobs: fail-fast: false matrix: module: - # `sources`: every tracked directory the module is built from (its cache key). + # `name`-windows is the module's entry in tools/scripts/native-inputs.py. - name: canvas-svg crate: canvas-svg-napi file: canvassvg.node addon-env: CANVAS_SVG_NAPI_ADDON - sources: crates/canvas-svg crates/canvas-svg-c crates/canvas-svg-napi crates/canvas-utils skia: true # Runners have no audio device: its suite renders offline and on the 'none' sink. - name: audio-context crate: audio-context-napi file: audiocontext.node addon-env: AUDIO_CONTEXT_NAPI_ADDON - sources: crates/audio-context-napi - name: canvas-media crate: canvas-media-napi file: canvasmedia.node addon-env: CANVAS_MEDIA_NAPI_ADDON - sources: crates/canvas-media-napi # no Node-API test suite - name: canvas-gamepad crate: canvas-gamepad-napi file: canvasgamepad.node - sources: crates/canvas-gamepad-napi arch: [x64, arm64] include: - arch: x64 @@ -473,43 +531,37 @@ jobs: MODULE_DIR: packages/${{ matrix.module.name }}/platforms/windows/${{ matrix.arch }} steps: - uses: actions/checkout@v4 - # The tree hashes of what the module is built from: equal hashes, equal module. - - name: Source key - id: sources - run: | - key=$(for path in ${{ matrix.module.sources }} crates/vendor/napi-sys Cargo.toml tools/scripts/build-napi.sh; do git rev-parse "HEAD:$path" || exit 1; done | sha256sum | cut -c1-32) - echo "key=$key" >> "$GITHUB_OUTPUT" - - name: Restore cached module - id: cache - uses: actions/cache@v4 + - uses: ./.github/actions/native-cache + id: native with: - path: ${{ env.MODULE_DIR }}/${{ matrix.module.file }} - key: ${{ env.NATIVE_CACHE_VERSION }}-${{ matrix.module.name }}-windows-${{ matrix.arch }}-${{ steps.sources.outputs.key }} + artifact: ${{ matrix.module.name }}-windows + variant: ${{ toJSON(matrix) }} + path: ${{ env.MODULE_DIR }}/ - uses: ./.github/actions/setup-windows-native - if: steps.cache.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' with: target: ${{ matrix.target }} - uses: ./.github/actions/skia-cache - if: steps.cache.outputs.cache-hit != 'true' && matrix.module.skia + if: steps.native.outputs.hit != 'true' && matrix.module.skia with: name: ${{ matrix.module.name }}-windows-${{ matrix.arch }} - uses: actions/setup-node@v4 - if: steps.cache.outputs.cache-hit != 'true' && matrix.arch == 'x64' && matrix.module.addon-env + if: steps.native.outputs.hit != 'true' && matrix.arch == 'x64' && matrix.module.addon-env with: node-version: '22' - name: Build ${{ matrix.module.file }} - if: steps.cache.outputs.cache-hit != 'true' + if: steps.native.outputs.hit != 'true' run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi ${{ matrix.module.crate }} # arm64 is cross-compiled, so only x64 runs them. The timeout bounds a test process that # hangs on exit (an addon releasing Media Foundation / D3D objects during process shutdown). # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache - if: steps.cache.outputs.cache-hit != 'true' && matrix.module.skia + if: steps.native.outputs.hit != 'true' && matrix.module.skia with: name: ${{ matrix.module.name }}-windows-${{ matrix.arch }} save: 'true' - name: Node-API tests - if: steps.cache.outputs.cache-hit != 'true' && matrix.arch == 'x64' && matrix.module.addon-env + if: steps.native.outputs.hit != 'true' && matrix.arch == 'x64' && matrix.module.addon-env timeout-minutes: 5 run: | export ${{ matrix.module.addon-env }}="$(cygpath -w "$PWD/$MODULE_DIR/${{ matrix.module.file }}")" @@ -535,23 +587,35 @@ jobs: runner: ubuntu-22.04-arm steps: - uses: actions/checkout@v4 + - uses: ./.github/actions/native-cache + id: native + with: + artifact: linux + variant: ${{ toJSON(matrix) }} + path: packages/*/platforms/linux/lib/${{ matrix.arch }}/ - uses: ./.github/actions/setup-linux-native + if: steps.native.outputs.hit != 'true' - uses: ./.github/actions/skia-cache + if: steps.native.outputs.hit != 'true' with: name: linux-${{ matrix.arch }} - uses: actions/setup-node@v4 + if: steps.native.outputs.hit != 'true' with: node-version: '22' - name: Build the Node-API modules + if: steps.native.outputs.hit != 'true' run: ./tools/scripts/build-linux.sh # Mesa's surfaceless EGL (llvmpipe) for 2D / WebGL and lavapipe for WebGPU: no GPU here. # canvas-media's suite drives Media Foundation, so it is Windows only. # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache + if: steps.native.outputs.hit != 'true' with: name: linux-${{ matrix.arch }} save: 'true' - name: Node-API tests + if: steps.native.outputs.hit != 'true' env: CANVAS_NAPI_ADDON: ${{ github.workspace }}/packages/canvas/platforms/linux/lib/${{ matrix.arch }}/canvasnative.node CANVAS_SVG_NAPI_ADDON: ${{ github.workspace }}/packages/canvas-svg/platforms/linux/lib/${{ matrix.arch }}/canvassvg.node diff --git a/.github/workflows/npm_release.yml b/.github/workflows/npm_release.yml index d477867b7..827e826e0 100644 --- a/.github/workflows/npm_release.yml +++ b/.github/workflows/npm_release.yml @@ -7,9 +7,12 @@ # Every native artifact build-native.yml produces (Android AARs, iOS/visionOS/tvOS # xcframeworks, Windows and Linux Node-API modules) is built from the tag and placed before # packaging, replacing any committed copy, so npm ships what CI built from the tagged -# sources. The committed binaries are only what local development uses; the xcframeworks -# are not committed at all. canvas-polyfill's async-release.aar is the one native artifact -# that still ships as committed. +# sources. `fresh: true` skips the cached outputs that pull requests and master reuse, which +# keep the crates.io versions and toolchains of whenever they were built (Skia's prebuilt +# libraries still restore through skia-cache, as before), and a reused native_run_id must be +# an earlier run of this workflow on the same tag. The committed +# binaries are only what local development uses; the xcframeworks are not committed at all. +# canvas-polyfill's async-release.aar is the one native artifact that still ships as committed. # # Running on the tag also keeps the build's caches safe: a run can restore master's cache # entries but saves only into its own ref's scope, so nothing a release executes can @@ -44,7 +47,7 @@ on: workflow_dispatch: inputs: native_run_id: - description: 'Reuse native artifacts from this earlier run of the same tag instead of rebuilding' + description: 'Reuse native artifacts from this earlier npm Release run of the same tag instead of rebuilding (checked)' required: false default: '' @@ -83,6 +86,8 @@ jobs: needs: [version] if: inputs.native_run_id == '' uses: ./.github/workflows/build-native.yml + with: + fresh: true publish: runs-on: ubuntu-latest @@ -110,6 +115,23 @@ jobs: corepack install -g npm@11.5.1 test "$(npm --version)" = "11.5.1" + # Master's Canvas Native runs upload artifacts under the same names, but theirs can be + # cached outputs of any age, so only an npm Release run of this tag at this commit may stand + # in. Its conclusion is not checked: the usual reason to reuse a run is that its publish + # failed after the native builds succeeded, and place-native-artifacts.sh fails on any + # artifact that is missing. + - name: Check native_run_id + if: inputs.native_run_id != '' + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ inputs.native_run_id }} + run: | + run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID" --jq '.path + " " + .head_branch + " " + .head_sha') + if [ "$run" != ".github/workflows/npm_release.yml $GITHUB_REF_NAME $GITHUB_SHA" ]; then + echo "::error::native_run_id $RUN_ID is a run of '$run', not of npm_release.yml on $GITHUB_REF_NAME at $GITHUB_SHA" + exit 1 + fi + - name: Download native artifacts uses: actions/download-artifact@v4 with: diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 2b3d19c08..8c7ef2756 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -35,14 +35,28 @@ jobs: - uses: actions/checkout@v4 - name: V8 bridge invariants run: python3 tools/tests/check-v8-bridge-invariants.py + # Every native cache key resolves and holds what its job reads, and every cached job skips + # its build on a hit. The npm job waits for this, so a key that misses a read publishes nothing. + - name: Native cache inputs + run: | + python3 tools/tests/test_native_inputs.py + python3 tools/tests/check-native-inputs.py unit-tests: name: Unit Tests runs-on: macos-15 steps: - uses: actions/checkout@v4 + # A pass is cached under the hash of what the tests build from, so unchanged code isn't + # retested. + - uses: ./.github/actions/native-cache + id: native + with: + artifact: unit-tests + path: .native-cache/unit-tests-passed # ~1.8 GB per entry: only master saves one, so pull requests don't crowd the 10 GB cache. - uses: actions/cache/restore@v4 + if: steps.native.outputs.hit != 'true' id: test-cache with: path: | @@ -58,11 +72,14 @@ jobs: # the macOS dylib build, and libtest cannot link against that, so the # rustflags are overridden for this run only. - name: Rust unit tests + if: steps.native.outputs.hit != 'true' env: RUSTFLAGS: '-C link-arg=-undefined -C link-arg=dynamic_lookup' - run: cargo test -p canvas-c --features 2d,webgl,gl + run: | + cargo test -p canvas-c --features 2d,webgl,gl + mkdir -p .native-cache && date -u > .native-cache/unit-tests-passed - uses: actions/cache/save@v4 - if: steps.test-cache.outputs.cache-hit != 'true' && github.event_name == 'push' && github.ref == 'refs/heads/master' + if: steps.native.outputs.hit != 'true' && steps.test-cache.outputs.cache-hit != 'true' && github.event_name == 'push' && github.ref == 'refs/heads/master' with: path: | ~/.cargo/registry @@ -78,7 +95,7 @@ jobs: name: Npm Build if: ${{ github.event_name != 'pull_request' }} runs-on: ubuntu-22.04 - needs: [build-native] + needs: [static-checks, build-native] env: NPM_TAG: pr # Space separated; must match the packages/ directories. diff --git a/tools/scripts/native-inputs.py b/tools/scripts/native-inputs.py new file mode 100644 index 000000000..c69b7ab9d --- /dev/null +++ b/tools/scripts/native-inputs.py @@ -0,0 +1,523 @@ +#!/usr/bin/env python3 +"""Computes the cache key of each native build output in CI: a hash of the tracked files the output +may be built from, read from git at a commit, so it is the same on every runner and the working tree +does not affect it. .github/actions/native-cache restores a job's output under this key and skips +the build on a hit; this docstring is the one description of what the key covers. + + native-inputs.py ARTIFACT [REV] the key + native-inputs.py --explain ARTIFACT [REV] each input with its git mode and object id (the key + hashes this) + native-inputs.py --verbose ARTIFACT [REV] the key, with the --explain lines on stderr + native-inputs.py --list the artifact names + --job ID, --variant V as the action passes them: fail unless job ID is one of + ARTIFACT's, and unless a matrix job passes its matrix + +A key covers every tracked file except those the artifact is known not to read, so a file nobody +has placed rebuilds every output rather than none: + * crates: those in its entry in ARTIFACTS and every workspace crate they reach through path + dependencies, as `cargo metadata` reports them for the commit's manifests, with every crate dir + that is not a workspace member (the [patch] targets under crates/vendor), the root Cargo.toml, + .cargo/, rust-toolchain* and Cargo.lock. Of the other members, the dependencies each declares + and its rust-version: Cargo.lock is not committed, so cargo resolves one set of versions for the + whole workspace, and a requirement in any member can move what every build links. An artifact + without crates reads none of these; + * workflows: the blocks of its jobs (one, but for the xcframeworks, which also have a lookup job + and the jobs that build their parts) and their workflows' settings above `jobs:` (comment lines + dropped, `run: |` text kept as written), so editing one job rebuilds only what it builds; no + workflow file; + * actions: the dirs of the local actions its jobs use (`uses: ./dir`; naming one any other way is + refused), those they use, and the native-cache action; no other action; + * every other file whose last matching rule in OWNERS names the artifact, or that no rule matches. + +OWNERS and ARTIFACTS are claims about what each job reads. tools/tests/check-native-inputs.py, which +Static Checks runs, holds them to what the jobs are seen to read and checks how the jobs are wired. + +Crates.io versions float within the declared ranges, and toolchains float within their pins. Neither +is part of the key. The cache action adds the week to the key so nothing reused is more than a week +old, and the release (npm_release.yml) builds with `fresh: true`. + +Needs git, Python 3.8+ and cargo (no network: `metadata --no-deps --offline` fetches nothing). +""" +import argparse +import functools +import hashlib +import io +import json +import os +import posixpath +import re +import subprocess +import sys +import tarfile +import tempfile + +BUILD_NATIVE = ".github/workflows/build-native.yml" +CACHE_ACTION = ".github/actions/native-cache" +NAPI_CRATES = ["crates/canvas-napi", "crates/canvas-svg-napi", "crates/audio-context-napi", + "crates/canvas-media-napi", "crates/canvas-gamepad-napi"] + + +def napi_windows(): + return {"crates": NAPI_CRATES, "jobs": [(BUILD_NATIVE, "napi-windows")]} + + +def apple(artifact, parts, crate): + """An xcframework built in parts: its lookup job, the jobs that build the parts, and its own.""" + return {"crates": [crate], "jobs": [(BUILD_NATIVE, f"{artifact}-cache"), (BUILD_NATIVE, parts), + (BUILD_NATIVE, artifact)]} + + +# crates: the crate dirs it builds. jobs: the workflow and id of each job that builds it, when not +# just build-native.yml's job of the artifact's name. build-napi.sh and build-linux.sh name every +# Node-API crate, so each Node-API build keys them all. +ARTIFACTS = { + "canvas-android": {"crates": ["crates/canvas-android"]}, + "canvas-ios": apple("canvas-ios", "canvas-apple", "crates/canvas-ios"), + "canvas-svg-android": {"crates": ["crates/canvas-svg-android", "crates/canvas-svg-c"]}, + "canvas-svg-ios": apple("canvas-svg-ios", "canvas-svg-apple", "crates/canvas-svg-ios"), + "audio-context-android": {}, + "audio-context-ios": {}, + "canvas-windows": {"crates": NAPI_CRATES}, + "canvas-svg-windows": napi_windows(), + "audio-context-windows": napi_windows(), + "canvas-media-windows": napi_windows(), + "canvas-gamepad-windows": napi_windows(), + "linux": {"crates": NAPI_CRATES}, + "unit-tests": {"crates": ["crates/canvas-c"], "jobs": [(".github/workflows/pull-request.yml", "unit-tests")]}, +} +EVERYONE = tuple(ARTIFACTS) +NONE = () +ANDROID = ("canvas-android", "canvas-svg-android", "audio-context-android") +APPLE = ("canvas-ios", "canvas-svg-ios", "audio-context-ios") +MOBILE = ANDROID + APPLE +WINDOWS = ("canvas-windows", "canvas-svg-windows", "audio-context-windows", "canvas-media-windows", + "canvas-gamepad-windows") +LINUX = ("linux",) +# The jobs that run make, and those that fetch V8's headers and runtime. +MAKE = ("canvas-android", "canvas-ios", "canvas-svg-android", "canvas-svg-ios") +V8 = ("canvas-android", "canvas-ios", "canvas-svg-android") +SCRIPTS = [ + (("canvas-android",), "build-android"), + (("canvas-svg-android",), "build-svg-android copy-svg-android"), + (("canvas-android", "canvas-svg-android"), "build-android-v8-stub"), + (("canvas-ios",), "build-ios canvas-build canvas-build-debug"), + (("canvas-svg-ios",), "canvas-svg-build canvas-svg-build-debug"), + (("audio-context-ios",), "audio-context-build"), + (V8, "download-v8"), + (WINDOWS, "build-napi download-angle"), + (LINUX, "build-linux"), + # Release steps, which run on what the builds produced, the apps' download of the release's + # frameworks (each release bumps its version), and the maintainers' scripts no job runs. + (NONE, "place-native-artifacts release-ios-binaries download-ios-frameworks release repack android-build " + "copy-android copy-android-libs busy-trace busy-bench build-headers"), +] +# The package dirs each build reads: its native sources and the platform dir it writes its output +# to (with the package's app-side files there). +PACKAGE_DIRS = { + "canvas-android": ["packages/canvas/src-native/canvas-android", "packages/canvas/platforms/android"], + "canvas-ios": ["packages/canvas/src-native/canvas-ios", "packages/canvas/platforms/ios"], + "canvas-svg-android": ["packages/canvas-svg/src-native/android", "packages/canvas-svg/platforms/android"], + "canvas-svg-ios": ["packages/canvas-svg/src-native/ios", "packages/canvas-svg/platforms/ios"], + "audio-context-android": ["packages/audio-context/src-native/android", "packages/audio-context/platforms/android"], + "audio-context-ios": ["packages/audio-context/src-native/ios", "packages/audio-context/platforms/ios"], + "canvas-windows": ["packages/canvas/platforms/windows"], + "canvas-svg-windows": ["packages/canvas-svg/platforms/windows"], + "audio-context-windows": ["packages/audio-context/platforms/windows"], + "canvas-media-windows": ["packages/canvas-media/platforms/windows"], + "canvas-gamepad-windows": ["packages/canvas-gamepad/platforms/windows"], + "linux": ["packages/*/platforms/linux"], +} + +# Which artifacts read the files outside the crates and .github: claims that +# tools/tests/check-native-inputs.py holds the jobs to. The last rule that matches a path decides, +# and a path no rule matches is read by every artifact. A rule is a file or dir (`*` stands for one +# path segment), or `*.ext` for every such file. +OWNERS = [ + # The npm packages' TypeScript, docs and manifests, the demos, the JS tooling, and the patches + # maintainers apply by hand. + ("*.ts", NONE), ("*.md", NONE), ("*.json", NONE), ("apps", NONE), ("tools/demo", NONE), + ("tools/assets", NONE), ("tools/schematics", NONE), ("tools/tests", NONE), + ("tools/workspace-scripts.js", NONE), ("tools/patches", NONE), ("packages/.gitkeep", NONE), + *((name, NONE) for name in (".editorconfig", ".eslintignore", ".gitignore", ".husky", ".npmrc", ".npsrc", + ".nxignore", ".prettierignore", ".prettierrc", ".travis.yml", ".vscode", "LICENSE")), + # Only audio-context-android checks out a submodule (Oboe). + (".gitmodules", ("audio-context-android",)), + # Only Apple's builds read Swift packages and pods, which name V8's headers too. + ("Makefile", MAKE), ("V8_RELEASE", V8), ("NATIVESCRIPT_IOS_RUNTIME_REF", V8), ("nativescript-v8", V8 + APPLE), + ("CanvasNative.podspec", APPLE), ("NativeScript.podspec", APPLE), ("Package.swift", APPLE), + *((f"tools/scripts/{name}.sh", who) for who, names in SCRIPTS for name in names.split()), + # It only computes the keys. + ("tools/scripts/native-inputs.py", NONE), + # A package's platform dirs hold the files apps build from and the committed outputs; the + # builds read none but their own output's (PACKAGE_DIRS). + ("packages/*/src-native", MOBILE), ("packages/*/platforms", NONE), + # Its native code ships committed (async-release.aar); no job builds it. + ("packages/canvas-polyfill", NONE), + # No job runs it; the Node-API suites are under the crates. + ("packages/canvas-gamepad/__test__", NONE), + *((d, (artifact,)) for artifact, dirs in PACKAGE_DIRS.items() for d in dirs), + # The C++ the Android CMake builds compile; the iOS frameworks do not (the apps' pods do). + ("packages/canvas/platforms/ios/src/cpp", ("canvas-android",)), + ("packages/canvas-svg/platforms/ios/src/cpp", ("canvas-svg-android",)), + # canvassvg's CMake borrows canvas's JNI headers. + ("packages/canvas/src-native/canvas-android/canvas/src/main/cpp", ("canvas-android", "canvas-svg-android")), + # Test fixtures of the Node-API suites, which every Node-API build keys with the crates. + ("apps/demo/src/assets/file-assets/audio", WINDOWS + LINUX), + ("tools/demo/canvas/assets/webgpu/pano.mp4", WINDOWS + LINUX), +] + +RUST_ROOT = re.compile(r"^(Cargo\.toml|Cargo\.lock|rust-toolchain(\.toml)?|\.cargo/.*)$") +LOCAL_USE = re.compile(r"^\s*(?:-\s+)?uses:\s*['\"]?\./([^\s'\"@#]+)") +COMMENT = r"(?:\s+#.*)?" + + +class Failure(Exception): + pass + + +def git(*args, data=None, binary=False): + result = subprocess.run(["git", "-c", "core.quotepath=off", *args], input=data, capture_output=True) + if result.returncode != 0: + raise Failure(f"git {' '.join(args[:2])}: {result.stderr.decode(errors='replace').strip()}") + return result.stdout if binary else result.stdout.decode("utf-8") + + +@functools.lru_cache(maxsize=None) +def show(rev, path): + return git("show", f"{rev}:{path}").replace("\r", "") + + +@functools.lru_cache(maxsize=None) +def tree_entries(rev): + """{path: (type, `mode id`)} of every tree, blob and submodule at rev.""" + entries = {} + for record in git("ls-tree", "-r", "-t", "-z", rev).split("\0"): + if record: + meta, path = record.split("\t", 1) + mode, kind, oid = meta.split() + entries[path] = (kind, f"{mode} {oid}") + return entries + + +@functools.lru_cache(maxsize=None) +def tracked(rev): + return frozenset(p for p, (kind, _) in tree_entries(rev).items() if kind != "tree") + + +def blob_id(text): + data = text.encode("utf-8") + return hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest() + + +def norm(path): + """Resolves . and .. in a repo-relative path; a path above the repo is an error.""" + parts = [] + for part in path.replace("\\", "/").split("/"): + if part in ("", "."): + continue + if part == "..": + if not parts: + raise Failure(f"'{path}' points above the repo") + parts.pop() + else: + parts.append(part) + return "/".join(parts) + + +def matches(rule, path): + if rule.startswith("*."): + return path.endswith(rule[1:]) + want, have = rule.split("/"), path.split("/") + return len(have) >= len(want) and all(w in ("*", h) for w, h in zip(want, have)) + + +@functools.lru_cache(maxsize=None) +def owners(path): + """The artifacts that read a file outside the crates and .github, by OWNERS (cached: after + changing OWNERS, call owners.cache_clear()).""" + found = EVERYONE + for rule, who in OWNERS: + if matches(rule, path): + found = who + return found + + +def indent(line): + return len(line) - len(line.lstrip(" ")) + + +def key_indent(line): + """The column of a line's key, past any `- ` list marker.""" + stripped = line.lstrip(" ") + return indent(line) + len(stripped) - len(stripped.lstrip("- ")) + + +def yaml_lines(text): + """(line, in_scalar) for each line, without YAML comments and blank lines outside block scalars + (`key: |` text), which are kept as written.""" + out, scalar = [], None + for line in text.split("\n"): + if scalar is not None: + if not line.strip() or indent(line) > scalar: + out.append((line, True)) + continue + scalar = None + if not line.strip() or line.lstrip().startswith("#"): + continue + out.append((line, False)) + if re.search(r":\s*[|>][-+0-9]*" + COMMENT + r"\s*$", line): + scalar = key_indent(line) + return out + + +@functools.lru_cache(maxsize=None) +def workflow(path, rev): + """(header, {job id: block}) of a workflow; refuses what a job block would not show.""" + problems, header, jobs, in_jobs, job = [], [], {}, False, None + for line, in_scalar in yaml_lines(show(rev, path)): + if not in_scalar and re.search(r"(:|-)\s+[&*][A-Za-z0-9_][A-Za-z0-9_-]*(\s|$)|<<:", line): + problems.append(f"YAML anchor or alias: {line.strip()}") + if re.match(r"^jobs:" + COMMENT + r"\s*$", line): + in_jobs = True + continue + if not in_jobs: + if "working-directory:" in line and not in_scalar: + problems.append(f"workflow-wide working-directory: {line.strip()}") + header.append(line) + continue + if not in_scalar and re.match(r"^\S", line): + problems.append(f"top-level key after jobs: {line.strip()}") + m = None if in_scalar else re.match(r"^ ([A-Za-z0-9_-]+):" + COMMENT + r"\s*$", line) + if m: + job = m.group(1) + jobs[job] = [] + if job: + jobs[job].append(line) + if problems: + raise Failure(f"{path}: " + "; ".join(problems)) + return "\n".join(header) + "\n", {j: "\n".join(lines) + "\n" for j, lines in jobs.items()} + + +def jobs_of(artifact): + return ARTIFACTS[artifact].get("jobs", [(BUILD_NATIVE, artifact)]) + + +def job_blocks(artifact, rev): + """[(workflow path, job id, the workflow's header, the job's block)] of each job that builds it.""" + out = [] + for path, job_id in jobs_of(artifact): + header, jobs = workflow(path, rev) + if job_id not in jobs: + raise Failure(f"no job '{job_id}' in {path} at {rev}") + out.append((path, job_id, header, jobs[job_id])) + return out + + +def steps_of(text, key_column, where): + """Splits a job block or an action's runs: section at its `steps:` key into (its other lines, the + job-level keys before and after the steps, and [step lines]). Steps may sit two columns in or, + compact, at the key's own column.""" + lines = text.split("\n") + start = next((i for i, line in enumerate(lines) + if re.match(rf"^{' ' * key_column}steps:" + COMMENT + r"\s*$", line)), None) + if start is None: + raise Failure(f"{where}: no steps") + rest = [line for line in lines[start + 1:] if line.strip()] + item = next((" " * c + "- " for c in (key_column + 2, key_column) if rest and rest[0].startswith(" " * c + "- ")), None) + steps, end = [], len(lines) + for i, line in enumerate(lines[start + 1:], start + 1): + if item and line.startswith(item): + steps.append([]) + elif line.strip() and indent(line) <= key_column: + end = i + break + if steps: + steps[-1].append(line) + if not steps: + raise Failure(f"{where}: no steps could be read under `steps:`") + return lines[:start] + lines[end:], steps + + +@functools.lru_cache(maxsize=None) +def crate_meta(rev): + """(deps, names, crate dirs, requirements) at rev: each workspace member's path dependencies and + each package name's dir, as `cargo metadata` reports them for the commit's manifests, every dir + with a Cargo.toml, and what decides the versions cargo resolves for the workspace: each member's + declared dependencies and rust-version.""" + tree = tracked(rev) + crate_dirs = tuple(sorted(p[: -len("/Cargo.toml")] for p in tree if p.endswith("/Cargo.toml"))) + root = sorted({"Cargo.toml", *(p for p in tree if RUST_ROOT.match(p))}) + archive = git("archive", "--format=tar", rev, "--", *root, *crate_dirs, binary=True) + with tempfile.TemporaryDirectory() as tmp: + with tarfile.open(fileobj=io.BytesIO(archive)) as tar: + if hasattr(tarfile, "data_filter"): + tar.extractall(tmp, filter="data") + else: + tar.extractall(tmp) + try: + # Run outside the repo, so a committed rust-toolchain file does not make rustup install + # its toolchain just to read manifests. + result = subprocess.run(["cargo", "metadata", "--no-deps", "--format-version", "1", "--offline", + "--manifest-path", os.path.join(tmp, "Cargo.toml")], + capture_output=True, stdin=subprocess.DEVNULL, cwd=tempfile.gettempdir()) + except FileNotFoundError: + raise Failure("cargo is not installed") + if result.returncode != 0: + raise Failure(f"cargo metadata at {rev}: {result.stderr.decode(errors='replace').strip()}") + meta = json.loads(result.stdout) + workspace = meta["workspace_root"].replace("\\", "/").rstrip("/") + "/" + + def rel(path): + path = path.replace("\\", "/") + if not path.startswith(workspace): + raise Failure(f"path dependency outside the workspace: {path}") + return path[len(workspace):] + + deps, names, requirements = {}, {}, {} + for package in meta["packages"]: + member = rel(posixpath.dirname(package["manifest_path"].replace("\\", "/"))) + deps[member] = [rel(dep["path"]) for dep in package["dependencies"] if dep.get("path")] + names[package["name"]] = member + declared = [{k: v for k, v in dep.items() if k != "path"} for dep in package["dependencies"]] + requirements[member] = {"rust_version": package.get("rust_version"), + "dependencies": sorted(declared, key=lambda d: json.dumps(d, sort_keys=True))} + return deps, names, crate_dirs, requirements + + +def closure(rev, start): + """The crate dirs an artifact building start reads: start, the members they reach by path, and + every crate dir that is not a member. Nothing when start is empty.""" + deps, _, crate_dirs, _ = crate_meta(rev) + if not start: + return set() + seen, queue = set(), list(start) + while queue: + crate = queue.pop() + if crate in seen: + continue + if crate not in deps: + raise Failure(f"{crate} is not a workspace member at {rev}") + seen.add(crate) + queue.extend(deps[crate]) + return seen | {d for d in crate_dirs if d not in deps} + + +def used_actions(rev, text, where): + """The local actions a job uses, and those they use, with the native-cache action.""" + found, todo, tree = {CACHE_ACTION}, [text], tracked(rev) + while todo: + for line in todo.pop().split("\n"): + m = LOCAL_USE.match(line) + if m is None and re.search(r"\buses['\"]?\s*:\s*['\"]?\.\.?/", line): + raise Failure(f"{where}: write a local action as `uses: ./dir` on its own line: {line.strip()}") + p = norm(m.group(1)) if m else None + if p is None or p in found: + continue + found.add(p) + manifest = next((f"{p}/{n}" for n in ("action.yml", "action.yaml") if f"{p}/{n}" in tree), None) + if manifest is None: + raise Failure(f"{where}: {p} is used as an action but has no action.yml at {rev}") + todo.append(show(rev, manifest)) + return found + + +def key_filter(artifact, rev): + """Whether a tracked path is one of the artifact's inputs.""" + actions = set().union(*(used_actions(rev, block, f"{path}#{job_id}") for path, job_id, _, block in job_blocks(artifact, rev))) + crates = closure(rev, ARTIFACTS[artifact].get("crates", [])) + crate_dirs = sorted(crate_meta(rev)[2], key=len, reverse=True) + + def wanted(p): + if p.startswith(".github/workflows/"): + return False + if any(p.startswith(a + "/") for a in actions): + return True + if p.startswith(".github/actions/"): + return False + crate = next((d for d in crate_dirs if p.startswith(d + "/")), None) + if crate is not None: + return crate in crates + if RUST_ROOT.match(p): + return bool(crates) + return artifact in owners(p) + return wanted + + +def key_inputs(artifact, rev): + """The artifact's inputs as `kind id path` lines: each wanted file by its mode and id, a dir whose + files are all wanted by its tree's, the blocks of its jobs and their workflows' headers, and with + crates, what the workspace's resolution reads.""" + wanted, entries = key_filter(artifact, rev), tree_entries(rev) + children = {} + for p in entries: + children.setdefault(posixpath.dirname(p), []).append(p) + + @functools.lru_cache(maxsize=None) + def whole(p): + if entries[p][0] != "tree": + return wanted(p) + return all([whole(c) for c in children[p]]) + + lines = {} + for path, job_id, header, block in job_blocks(artifact, rev): + lines[f"{path}#{job_id}"] = f"block {blob_id(block)}" + lines[f"{path}#header"] = f"block {blob_id(header)}" + if ARTIFACTS[artifact].get("crates"): + lines["Cargo resolution"] = f"deps {blob_id(json.dumps(crate_meta(rev)[3], sort_keys=True))}" + todo = [""] + while todo: + for p in children.get(todo.pop(), []): + if whole(p): + lines[p] = entries[p][1] + elif entries[p][0] == "tree": + todo.append(p) + return "".join(f"{lines[p]} {p}\n" for p in sorted(lines)) + + +def resolve(rev): + try: + return git("rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}").strip() + except Failure: + raise Failure(f"no commit '{rev}'") + + +def main(argv): + parser = argparse.ArgumentParser(prog="native-inputs.py", description="the cache keys of the native build outputs") + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--list", action="store_true") + mode.add_argument("--explain", action="store_true") + mode.add_argument("--verbose", action="store_true") + parser.add_argument("--job") + parser.add_argument("--variant") + parser.add_argument("artifact", nargs="?") + parser.add_argument("rev", nargs="?", default="HEAD") + args = parser.parse_args(argv) + out = sys.stdout.buffer + if args.list: + out.write("".join(f"{a}\n" for a in ARTIFACTS).encode()) + return 0 + if args.artifact not in ARTIFACTS: + raise Failure(f"unknown artifact '{args.artifact}' (one of: {' '.join(ARTIFACTS)})") + rev = resolve(args.rev) + if args.job is not None: + block = next((b for _, job_id, _, b in job_blocks(args.artifact, rev) if job_id == args.job), None) + if block is None: + raise Failure(f"job '{args.job}' does not build '{args.artifact}'") + if (args.variant or "").strip() in ("", "null") and any(re.match(r"^\s+matrix:", l) for l in steps_of(block, 4, args.job)[0]): + raise Failure(f"{args.job} is a matrix job: pass `variant: ${{{{ toJSON(matrix) }}}}`, or its legs share one key") + lines = key_inputs(args.artifact, rev) + if args.explain: + out.write(lines.encode()) + else: + if args.verbose: + sys.stderr.buffer.write(lines.encode()) + out.write((blob_id(lines)[:32] + "\n").encode()) + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main(sys.argv[1:])) + except Failure as error: + sys.stderr.write(f"native-inputs: {error}\n") + sys.exit(1) diff --git a/tools/tests/check-native-inputs.py b/tools/tests/check-native-inputs.py new file mode 100644 index 000000000..a1e6c3e06 --- /dev/null +++ b/tools/tests/check-native-inputs.py @@ -0,0 +1,985 @@ +#!/usr/bin/env python3 +"""Holds the claims tools/scripts/native-inputs.py keys the native builds by (OWNERS, ARTIFACTS and +each artifact's crate closure) to what the jobs are seen to read, and checks that every cached job +is wired to its cache. Static Checks runs it. + + check-native-inputs.py [REV] REV defaults to HEAD + +A key leaves out only what OWNERS places elsewhere, the crates outside its closure, the other jobs' +blocks and the actions its job does not use, so a job can read what its key misses only across one +of those lines. Two passes look for reads across them. + +Reading the job: its steps and job-level keys, its actions' steps, the files they run and the files +those mention, what `make -n` prints for the targets it runs, and the scripts in the package dirs +OWNERS gives the artifact, followed in turn. It fails when a file read that way is outside the key, +a crate named that way (by package name or dir) is outside the closure, or the job cannot be read: +a file run that is not tracked, a file run after `cd`, a path above the repo, a script argument +(`bash build`) that is no file, `python -m`, a package runner, cargo building crates it does not +name, an unclosed quote or heredoc, a value continued on plain lines, `make` in any form but +`make [-jN] [VAR=x] ` from the repo root, a Makefile with conditionals, includes, $(shell) +or paths of the dir it runs in, a Makefile that reads a variable it does not set (or a `?=` +default in a path), which the environment would choose, a followed script that runs make (but the +third-party builds in OWN_MAKE) or sources a computed path, a local action without action.yml, a +workflow key after `jobs:`, a YAML anchor or alias, or a workflow- or job-wide working-directory. + +Scanning the key: every text file in the key (up to 2 MB; the larger ones here are binaries) but the +workflows, actions and Makefile, and the step and job-key text the first pass reads, are searched for +paths that lead out of the key. A path counts relative to the repo or to the file's dir; after a +variable the file sets (`set(DIR ...)`, `DIR=...`), with each of its values; after any other +variable, from either place; with a glob or another variable standing for one path segment, or for +the dir it is in when that matches nothing; given as the segments of a join() or resolve() call; +and naming a dir, for every file under it. Comments and the values variables are set to are not +paths; a path made with a matrix value is not checked, since the legs of one job can be different +artifacts (each leg's values are in its key); and crates' tests, benches and examples count only +for the jobs in CARGO_TESTS, which run `cargo test`. This pass holds the claims about build files, +such as the C++ the Android CMake builds compile from the iOS package dir. + +A path a file names but its job does not read there (one it writes, say) is listed in NOT_READ with +the reason, for both passes. + +Both fail on values that differ between runs that share a key: a ${{ }} context other than matrix, +steps, env, strategy, runner and github.workspace, in any case and in `.` or `[ ]` form, in the +workflow's settings, the job's keys, its build steps and its actions' steps (where `inputs.` is the +job's own `with:`), and the run's GITHUB_ variables (GITHUB_SHA, GITHUB_REF, ...) in the text the +first pass reads. + +And the wiring: each job that uploads an artifact in build-native.yml is one of an artifact's, and +one job of each artifact restores it: a native-cache step with `id: native` right after the +checkout, for its own artifact and the upload's path, with `variant: ${{ toJSON(matrix) }}` in a +matrix job, and every later step but the upload skipped on a hit (its `if:` is +`steps.native.outputs.hit != 'true'`, or that && more, with no ||). An artifact built by several +jobs (the xcframeworks) also has a lookup job, which is the checkout and the step with +`lookup-only: 'true'` and has its `hit` and `key` as outputs; each other job that builds a part of +it needs the lookup and has `if: needs..outputs.hit != 'true'` (or that && more, with no +||), and the restore passes `key: ${{ needs..outputs.key }}`, so both use the same week. +For the reader, a make target made of a matrix value counts once per value the strategy lists. + +Needs git, Python 3.8+, cargo and make. +""" +import argparse +import collections +import functools +import importlib.util +import os +import posixpath +import re +import subprocess +import sys +import tempfile + +sys.dont_write_bytecode = True # no __pycache__ beside the key module +_spec = importlib.util.spec_from_file_location( + "native_inputs", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "scripts", "native-inputs.py")) +ni = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(ni) + +# skia-cache names every platform's build scripts, only to hash them. +SKIA_CACHE = ".github/actions/skia-cache" +GUARD = "steps.native.outputs.hit != 'true'" +# Scripts that build a third-party library from its own sources with its own make. +OWN_MAKE = {f"packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/{name}" + for name in ("build_opus_deps.sh", "build_opus_deps_ios.sh")} +SCRIPT_EXT = r"(?:sh|bash|py|js|mjs|cjs|ts|rb|pl|ps1)" +SHELLS = {"sh", "bash", "zsh", "dash", "source", "."} +# The option that makes each interpreter run code given inline rather than a file. +INLINE_CODE = {**{s: {"-c"} for s in SHELLS}, "python": {"-c"}, "python3": {"-c"}, "py": {"-c"}, + "node": {"-e", "--eval", "-p", "--print"}, "ruby": {"-e"}, "perl": {"-e", "-E"}, + "pwsh": {"-Command", "-c", "-EncodedCommand"}, "powershell": {"-Command", "-c", "-EncodedCommand"}} +INTERPRETERS = set(INLINE_CODE) +# Interpreter options whose value is the next argument (so the script is the one after it). +VALUE_OPTIONS = {"-o", "+o", "-O", "+O", "-W", "-X", "-r", "--require", "--import", "--loader", + "-ExecutionPolicy", "-ep"} +# Commands that run the command after them, with their options that take a value. +WRAPPERS = {"sudo": {"-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U"}, "env": {"-u", "-C", "-S"}, + "nice": {"-n"}, "timeout": {"-s", "-k"}, "time": {"-f", "-o"}, "exec": {"-a"}, + "xargs": {"-n", "-I", "-P", "-L", "-s", "-d", "-E", "-a"}, "nohup": set(), "command": set(), + "arch": set()} +KEYWORDS = {"if", "then", "elif", "else", "while", "until", "do", "!", "{", "}"} +# Commands whose arguments name a program without running it: lookups, output, package installs. +NAMES_ONLY = {"which", "type", "hash", "echo", "printf", "apt", "apt-get", "brew", "choco", "dnf", "yum", + "pacman", "port", "apk", "winget", "zypper"} +PACKAGE_RUNNERS = {"npm", "npx", "yarn", "pnpm", "nx", "bun", "just"} +CARGO_BUILDS = {"build", "b", "test", "t", "check", "c", "run", "r", "bench", "clippy", "doc", "d", "rustc"} +WORKSPACE_PREFIX = re.compile(r"\$\{\{\s*github\.workspace\s*\}\}/|\$\{?(?:GITHUB_WORKSPACE|ROOT|REPO_ROOT|PWD)\}?/") +# A context in an expression, with the field it reads (`.x` or `['x']`), if any. +CONTEXT = re.compile(r"(?][-+0-9]*" + ni.COMMENT + r"\s*$", value): + body = [] + for rest in step[i + 1:]: + if rest.strip() and ni.indent(rest) <= ni.key_indent(line): + break + body.append(rest) + return "\n".join(body) + following = next((l for l in step[i + 1:] if l.strip()), "") + if following and ni.indent(following) > ni.key_indent(line): + raise ni.Failure(f"`{name}:` continues on the next lines; write it as `{name}: |` so it can be read") + value = re.sub(r"\s+#.*$", "", value).strip() + if len(value) > 1 and value[0] == value[-1] and value[0] in "'\"": + value = value[1:-1] + return value + return "" + + +def is_dynamic(token): + return re.search(r"[$*?{}\[\]]", token) is not None + + +def looks_like_file(token): + return "/" in token or re.search(r"\." + SCRIPT_EXT + "$", token) is not None + + +# What a script calls its own dir: `$(dirname "$0")`, `$(dirname "${BASH_SOURCE[0]}")`, +# `${BASH_SOURCE[0]%/*}`, `$SCRIPT_DIR`. +SCRIPT_DIR_REF = re.compile(r"\$\(\s*dirname\s+\"?\$(?:0|\{BASH_SOURCE\[0\]\}|BASH_SOURCE)\"?\s*\)" + r"|\$\{BASH_SOURCE\[0\]%/\*\}|\$\{?SCRIPT_DIR\}?") + + +def mentions(text, bases, tree, script_dir=None): + """The tracked files (not dirs) the text names, relative to the repo or to one of bases, and + with script_dir, to what the script calls its own dir. Workflow files are left out: each job's + own block is its input, and a script's message naming the ni.workflow (canvas-build.sh does) would + otherwise rebuild a job for an edit to any other job.""" + found = set() + text = WORKSPACE_PREFIX.sub("", text.replace("\\", "/")) + if script_dir is not None: + text = SCRIPT_DIR_REF.sub("@SCRIPT_DIR@", text) + for token in re.findall(r"[^\s'\"`=;&|()<>,]+", text): + token = token.rstrip(".:") + own = token.startswith("@SCRIPT_DIR@/") + if own: + token = token[len("@SCRIPT_DIR@/"):] + if is_dynamic(token): + continue + for base in ([script_dir] if own else ["", *bases]): + try: + path = ni.norm(posixpath.join(base, token)) + except ni.Failure: + continue + if path in tree and not path.startswith(".github/workflows/"): + found.add(path) + return found + + +def shell_commands(script, where): + """The commands in shell text, each a list of its words with quotes removed. Commands end at + ; & | ( ) ` $( and newlines outside quotes; text inside quotes stays in its word, so a word that + ran something computed keeps its `$`. A backslash escapes a quote, `$`, a space or another + backslash, and otherwise reads as `/` (the Windows jobs' paths). Heredoc bodies and redirection + targets are dropped. An unclosed quote is an error rather than a script swallowed whole.""" + commands, words, word, quote, i = [], [], None, None, 0 + heredocs, drop_next = [], False + + def end_word(): + nonlocal word, drop_next + if word is not None: + if drop_next: + drop_next = False + else: + words.append(word) + word = None + + def end_command(): + nonlocal words, drop_next + end_word() + if words: + commands.append(words) + words, drop_next = [], False + + while i < len(script): + c = script[i] + nxt = script[i + 1] if i + 1 < len(script) else "" + if quote: + if c == quote: + quote = None + elif c == "\\" and quote == '"' and nxt in '"$`\\': + word += nxt + i += 1 + else: + word += "/" if c == "\\" else c + elif c == "\\" and nxt and nxt in "'\"$ \\": + word = (word or "") + nxt + i += 1 + elif c in "'\"": + quote, word = c, word or "" + elif c == "#" and word is None: + while i < len(script) and script[i] != "\n": + i += 1 + continue + elif script.startswith("<<", i) and not script.startswith("<<<", i): + end_word() + m = re.match(r"<<-?\s*['\"]?([A-Za-z0-9_]+)['\"]?", script[i:]) + if not m: + raise ni.Failure(f"{where}: cannot read the heredoc at `{script[i:i + 20].strip()}`") + heredocs.append(m.group(1)) + i += m.end() + continue + elif c in "<>": + if word is not None and word.isdigit(): + word = None + end_word() + drop_next = True + while i + 1 < len(script) and script[i + 1] in "<>&": + i += 1 + elif script.startswith(("&&", "||", "$("), i): + end_command() + i += 2 + continue + elif c == "\n": + end_command() + while heredocs: + delimiter = heredocs.pop(0) + i += 1 + while i < len(script): + j = script.find("\n", i) + line = script[i:] if j < 0 else script[i:j] + i = len(script) if j < 0 else j + if line.strip() == delimiter: + break + i += 1 + else: + raise ni.Failure(f"{where}: the heredoc ending `{delimiter}` is not closed") + i -= 1 if i < len(script) else 0 + elif c in ";&|()`": + end_command() + elif c.isspace(): + end_word() + else: + word = (word or "") + ("/" if c == "\\" else c) + i += 1 + if quote: + raise ni.Failure(f"{where}: a {quote} quote is never closed, so what runs after it cannot be read") + if heredocs: + raise ni.Failure(f"{where}: the heredoc ending `{heredocs[0]}` is not closed") + end_command() + return commands + + +def is_absolute(token): + return token.startswith(("/", "~")) or re.match(r"^[A-Za-z]:/", token) is not None + + +def matrix_values(strategy): + """{key: [values]} of the matrix keys a job's strategy lists inline (`platform: [ios, tvos]`).""" + return {m.group(1): [v.strip().strip("'\"") for v in m.group(2).split(",")] + for m in (re.match(r"^\s+([\w-]+):\s*\[([^\]]*)\]\s*$", line) for line in strategy) if m} + + +def each_leg(script, values): + """The script with each word that holds a matrix value the strategy lists written once per value, + so `make ${{ matrix.platform }}` reads as one make of every leg's target.""" + def legs(m): + options = values.get(m.group(2)) + return " ".join(m.group(0).replace(m.group(1), v) for v in options) if options else m.group(0) + return re.sub(r"[^\s'\"]*(\$\{\{\s*matrix\.([\w-]+)\s*\}\})[^\s'\"]*", legs, script) + + +def commands(step, where, values=None): + """What a step's run: text runs: (wd, files, guesses, make targets and variables). files must + exist; guesses are (what, path) for a script argument without `/` or extension, which has to.""" + wd = field(step, "working-directory") + files, guesses, makes = set(), [], [] + script = WORKSPACE_PREFIX.sub("", each_leg(re.sub(r"\\\n", " ", field(step, "run")), values or {})) + for line in script.split("\n"): + if re.search(r"(^|[\s;&|(!{])(?:\S*/)?g?make\s[^\n]*(\$\(|`|\$\{\{)", line): + raise ni.Failure(f"{where}: cannot follow make with a computed argument: `{line.strip()}`") + walk(script, wd, where, files, guesses, makes, False) + if len(makes) > 1: + raise ni.Failure(f"{where}: runs make more than once; give each its own step") + return wd, files, guesses, (makes[0] if makes else None) + + +def unwrap(tokens): + """The command a shell command runs, past keywords, assignments and wrappers with their + options; [] for `command -v`, which only looks one up.""" + while tokens: + word = tokens[0] + if word in WRAPPERS: + tokens = tokens[1:] + if word == "command" and tokens and tokens[0] in ("-v", "-V"): + return [] + while tokens and tokens[0].startswith("-"): + option, tokens = tokens[0], tokens[1:] + if option in WRAPPERS[word] and tokens: + tokens = tokens[1:] + if word == "timeout" and tokens and re.match(r"^\d+(\.\d+)?[smhd]?$", tokens[0]): + tokens = tokens[1:] + elif word in KEYWORDS or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", word): + tokens = tokens[1:] + else: + break + return tokens + + +def walk(script, wd, where, files, guesses, makes, after_cd): + for tokens in shell_commands(script, where): + command = " ".join(tokens) + tokens = unwrap(tokens) + if not tokens: + continue + name, args = tokens[0], tokens[1:] + base = posixpath.basename(name) + first = next((a for a in args if not a.startswith(("-", "+"))), "") + # A make that a wrapper this does not know starts (`chrt 10 make`) would read as an argument. + if base not in ("make", "gmake") and base not in NAMES_ONLY and any( + posixpath.basename(a) in ("make", "gmake") for a in args): + raise ni.Failure(f"{where}: cannot follow the make in `{command}`; run `make ` itself") + if base in PACKAGE_RUNNERS: + raise ni.Failure(f"{where}: `{command}` runs what a package manifest says; run the script itself") + if base == "cargo" and first in CARGO_BUILDS and not (wd or after_cd) and ( + {"--workspace", "--all"} & set(args) or not any( + a in ("-p", "--package", "--manifest-path") or a.startswith(("--package=", "--manifest-path=")) + or (a.startswith("-p") and not a.startswith("--")) for a in args)): + raise ni.Failure(f"{where}: `{command}` builds crates it does not name; name each with -p") + if name in ("cd", "pushd"): + after_cd = True + elif base in ("make", "gmake"): + makes.append(make_command(args, wd or after_cd, command, where)) + elif base in INTERPRETERS: + if base in ("python", "python3", "py") and "-m" in args: + raise ni.Failure(f"{where}: cannot tell which file `{command.strip()}` runs; run the file itself") + if base in SHELLS and "-c" in args: + code = args[args.index("-c") + 1] if args.index("-c") + 1 < len(args) else "" + after_cd = walk(code, wd, where, files, guesses, makes, after_cd) + continue + if any(a in INLINE_CODE[base] for a in args): + continue + script_arg, skip_value = None, False + for arg in args: + if skip_value: + skip_value = False + elif arg in VALUE_OPTIONS: + skip_value = True + elif not arg.startswith(("-", "+")): + script_arg = arg + break + if script_arg is None or is_dynamic(script_arg) or is_absolute(script_arg): + continue + if after_cd: + raise ni.Failure(f"{where}: runs `{command.strip()}` after `cd`; give the step a working-directory instead") + path = ni.norm(posixpath.join(wd, script_arg)) + if looks_like_file(script_arg): + files.add(path) + else: + guesses.append((f"{where}: `{command.strip()}`", path)) + elif "/" in name and not is_absolute(name) and not is_dynamic(name): + if after_cd: + raise ni.Failure(f"{where}: runs `{name}` after `cd`; give the step a working-directory instead") + files.add(ni.norm(posixpath.join(wd, name))) + return after_cd + + +def make_command(args, moved, command, where): + """([targets], [VAR=value]) of `make [-jN] [VAR=value] ` from the repo root.""" + if moved or any(re.match(r"^(-C|-f|--directory|--file|--makefile)", a) for a in args): + raise ni.Failure(f"{where}: only `make ` from the repo root is followed: `{command.strip()}`") + targets, variables, i = [], [], 0 + while i < len(args): + arg = args[i] + if arg in ("-j", "-l") and i + 1 < len(args) and re.match(r"^\d+$", args[i + 1]): + i += 1 + elif "=" in arg and not arg.startswith("-"): + variables.append(arg) + elif not arg.startswith("-"): + targets.append(arg) + i += 1 + if not targets: + raise ni.Failure(f"{where}: name the targets of `{command.strip()}`, so what it runs can be followed") + return targets, variables + + +def make_environment(makefile, variables): + """The variables a Makefile's commands can take from the environment: those it reads but never + sets (a function's own, `$(call f,x)`'s $(1) and $(foreach x,...)'s x, are set), and its `?=` + defaults where they make a path.""" + makefile = makefile.replace("$$", "") + set_here = set(re.findall(r"^\s*(?:export\s+|override\s+)?([A-Za-z_][\w.-]*)\s*(?::{1,3}=|\+=|\?=|=)", makefile, re.M)) + set_here |= {v.split("=", 1)[0] for v in variables} | set(re.findall(r"\$\(foreach\s+([\w.-]+)\s*,", makefile)) + defaults = set(re.findall(r"^\s*([A-Za-z_][\w.-]*)\s*\?=", makefile, re.M)) + found = [] + for m in re.finditer(r"\$[({]([A-Za-z_][\w.-]*)(?=[)}])", makefile): + name = m.group(1) + if name not in set_here and name not in ("MAKE", "MAKEFLAGS", "MAKECMDGOALS", "SHELL"): + found.append(name) + for name in defaults: + if re.search(rf"/\$[({{]{re.escape(name)}[)}}]|\$[({{]{re.escape(name)}[)}}]/", makefile): + found.append(name) + return sorted(set(found)) + + +def make_commands(rev, targets, variables): + """What `make -n` runs, with the commit's Makefile and no inherited variables. A Makefile that + can run other commands than it prints (conditionals, includes, $(shell)), that names the dir + make runs in, or whose commands the environment can change, is refused.""" + makefile = ni.show(rev, "Makefile") + if re.search(r"^\s*(ifeq|ifneq|ifdef|ifndef|-?include|sinclude)\b|^[^#\n]*!=" + r"|\$[({](shell|origin|wildcard|realpath|abspath|CURDIR)\b", makefile, re.M): + raise ni.Failure("the Makefile has conditionals, includes, $(shell) or paths of the dir make runs " + "in: `make -n` cannot show what a job runs") + for name in make_environment(makefile, variables): + raise ni.Failure(f"the Makefile reads {name} from the environment, which `make -n` does not see: set " + f"it in the Makefile (with =, or ?= where it names no path) or pass it as {name}=...") + with tempfile.TemporaryDirectory() as tmp: + try: + result = subprocess.run(["make", "-n", "-f", "-", *variables, *targets], input=makefile.encode(), + cwd=tmp, capture_output=True, env={"PATH": os.environ.get("PATH", "")}) + except FileNotFoundError: + raise ni.Failure("the job runs make, and make is not installed") + output = result.stdout.decode("utf-8").replace("\r", "") + if os.path.basename(tmp) in output: + raise ni.Failure(f"make -n {' '.join(targets)} prints the dir it ran in, so what it runs cannot be followed") + if result.returncode != 0: + raise ni.Failure(f"make -n {' '.join(targets)}: {result.stderr.decode(errors='replace').strip()}") + return output + + +def named_crates(rev, corpus): + """The members the text names by package name, as a word of its own (`-p canvas-ios`, not + packages/canvas/src-native/canvas-android), or by dir, after any prefix (`$ROOT/crates/x`).""" + _, names, _, _ = ni.crate_meta(rev) + return {member for name, member in names.items() + if re.search(rf"(?\[\]|&:!]*/[^\s'\"`=;,(){}<>\[\]|&:!]*") +# A path given as its segments: path.join(root, 'apps', 'demo'), os.path.join(ROOT, "x"). +JOIN = re.compile(r"\b(?:join|resolve)\(([^()]*)\)") +WILD, LEG = "\x01", "\x02" +WILDS = r"[*?" + WILD + "]" + + +@functools.lru_cache(maxsize=None) +def texts(rev): + """{path: text} of every tracked text file at rev up to 2 MB (those above it here are binaries).""" + ids = {} + for record in ni.git("ls-tree", "-r", "-l", "-z", rev).split("\0"): + if record: + meta, path = record.split("\t", 1) + _, kind, oid, size = meta.split() + if kind == "blob" and int(size) <= 2_000_000: + ids[path] = oid + missing = sorted({oid for oid in ids.values() if oid not in BLOBS}) + data = ni.git("cat-file", "--batch", data="".join(oid + "\n" for oid in missing).encode(), binary=True) + i = 0 + for oid in missing: + end = data.index(b"\n", i) + size = int(data[i:end].split()[2]) + blob = data[end + 1:end + 1 + size] + i = end + 2 + size + BLOBS[oid] = None if b"\0" in blob[:8000] else blob.decode("utf-8", errors="replace").replace("\r", "") + return {p: BLOBS[oid] for p, oid in ids.items() if BLOBS[oid] is not None} + + +BLOBS = {} # each blob's text, None for a binary, kept across revs +MATCHED = {} # the paths each pattern with a glob or variable matches, by (pattern, tree) + + +def expand(text, values): + """The text with each variable the file sets replaced by each of its values in turn, and any + other variable by WILD (a matrix value by LEG).""" + text = MATRIX_VALUE.sub(LEG, text) + m = VARIABLE.search(text) + if m is None: + return [text] + rests = expand(text[m.end():], values) + name = m.group(1) or m.group(2) or m.group(3) + options = (values.get(name) if name else None) or [WILD] + if len(options) * len(rests) > 64: + options = [WILD] + return [text[:m.start()] + option + rest for option in options for rest in rests] + + +def resolve_token(token, here, entries): + """The tracked files and dirs a path in a file can name: from the repo or the file's dir, with + WILD and globs standing for one segment, and from either after an unknown variable (with the + `..` after it, which leads from somewhere unknown). A computed name that matches nothing names + the dir it is in.""" + token = re.sub(r"^(" + WILD + r"/(\.\./)*)+", "", token).rstrip(".") + if token.startswith("/") or "//" in token or LEG in token: + return set() + segments = [s for s in token.split("/") if s] + if not any(re.search(r"[A-Za-z]", s) and not re.search(WILDS, s) for s in segments): + return set() + found = set() + for base in ("", here): + try: + path = ni.norm(posixpath.join(base, *segments)) + except ni.Failure: + continue + if not re.search(WILDS, path): + if path in entries: + found.add(path) + continue + parts = path.split("/") + if (path, id(entries)) not in MATCHED: + pattern = re.compile("^" + "/".join("[^/]*".join(map(re.escape, re.split(WILDS + "+", s))) for s in parts) + "$") + MATCHED[path, id(entries)] = {p for p in entries if pattern.match(p)} + matched = MATCHED[path, id(entries)] + literal = "/".join(parts[:next(i for i, s in enumerate(parts) if re.search(WILDS, s))]) + found |= matched or ({literal} if literal in entries else set()) + return found + + +def names(text, here, entries): + """The tracked files and dirs the text's paths name, from the repo or from here.""" + return set().union(*(resolve_token(token, here, entries) for token in path_tokens(text))) + + +@functools.lru_cache(maxsize=None) +def path_tokens(text): + """The paths the text names outside comments and the values it sets variables to, with the + variables it sets expanded.""" + values, found = {}, set() + + def define(name, value): + # A value that is not a plain path (a command's output, say) is unknown. + values.setdefault(name, []) + values[name] += [v if re.match(r"^[\w./@+" + WILD + "-]*$", v) else WILD + for v in expand(value.strip("'\""), values) if v not in values[name]] + + for line in text.split("\n"): + if COMMENT_LINE.match(line): + continue + cmake = CMAKE_SET.match(line) + if cmake: + define(cmake.group(2), cmake.group(3) + ("/.." if cmake.group(1).lower() != "set" else "")) + continue + for m in SHELL_SET.finditer(line): + define(m.group(1), m.group(2)) + for expanded in expand(SHELL_SET.sub(" ", line), values): + tokens = TOKEN.findall(expanded) + for m in JOIN.finditer(expanded): + args = [a.strip() for a in m.group(1).split(",")] + tokens.append("/".join(a[1:-1] if len(a) > 1 and a[0] == a[-1] and a[0] in "'\"" else WILD for a in args)) + found.update(tokens) + return tuple(sorted(found)) + + +@functools.lru_cache(maxsize=None) +def named_paths(rev, p): + return frozenset(names(texts(rev)[p], posixpath.dirname(p), ni.tree_entries(rev))) + + +@functools.lru_cache(maxsize=None) +def files_under(rev): + under = collections.defaultdict(list) + for p, (kind, _) in ni.tree_entries(rev).items(): + d = posixpath.dirname(p) if kind != "tree" else None + while d: + under[d].append(p) + d = posixpath.dirname(d) + return under + + +def crate_of(rev, p): + return next((d for d in sorted(ni.crate_meta(rev)[2], key=len, reverse=True) if p.startswith(d + "/")), None) + + +def crossings(artifact, rev, wanted, source, here, targets): + """The targets that source names and the artifact's key leaves out, but crate dirs (which name + crates), source itself and the dirs it is in, and NOT_READ's.""" + entries, under, problems = ni.tree_entries(rev), files_under(rev), [] + crate_dirs, crates = ni.crate_meta(rev)[2], ni.closure(rev, ni.ARTIFACTS[artifact].get("crates", [])) + for target in sorted(targets): + if (target in crate_dirs or target == source or target.startswith(".github/workflows/") + or here == target or here.startswith(target + "/") or not_read(source, target)): + continue + left_out = [f for f in (under[target] if entries[target][0] == "tree" else [target]) if not wanted(f)] + if left_out: + first, crate = left_out[0], crate_of(rev, left_out[0]) + whose = (f"{crate} is outside its crates' closure" if crate and crate not in crates else + f"OWNERS gives {first} to {', '.join(ni.owners(first)) or 'no artifact'}") + what = target if left_out == [target] else f"{len(left_out)} of the files under {target}" + problems.append(f"{artifact}: {source} names {what}, which its key leaves out ({whose}); if its " + f"job does not read it there, add it to NOT_READ with the reason") + return problems + + +def scan(artifact, rev, wanted): + """The paths that the text files in the artifact's key name and its key leaves out. The job + pass reads the workflows, actions and Makefile for what the job runs of them.""" + tested = set(ni.ARTIFACTS[artifact].get("crates", [])) if artifact in CARGO_TESTS else set() + problems = [] + for p in sorted(texts(rev)): + if p.startswith(".github/") or p == "Makefile" or not wanted(p): + continue + crate = crate_of(rev, p) + if crate and p[len(crate) + 1:].split("/")[0] in ("tests", "benches", "examples") and crate not in tested: + continue + problems += crossings(artifact, rev, wanted, p, posixpath.dirname(p), named_paths(rev, p)) + return problems + + +def main(argv): + parser = argparse.ArgumentParser(prog="check-native-inputs.py", + description="hold the native cache keys to what their jobs read") + parser.add_argument("rev", nargs="?", default="HEAD") + rev, problems = ni.resolve(parser.parse_args(argv).rev), [] + for artifact in ni.ARTIFACTS: + try: + ni.key_inputs(artifact, rev) + problems.extend(check_reads(artifact, rev)) + except ni.Failure as error: + problems.append(f"{artifact}: {error}") + if problems: + raise ni.Failure("\n ".join(["keys:", *problems])) + check_wiring(rev) + print(f"{len(ni.ARTIFACTS)} keys resolve and hold what their jobs read, and every cached job is wired right") + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main(sys.argv[1:])) + except ni.Failure as error: + sys.stderr.write(f"check-native-inputs: {error}\n") + sys.exit(1) diff --git a/tools/tests/test_native_inputs.py b/tools/tests/test_native_inputs.py new file mode 100644 index 000000000..71168fa1f --- /dev/null +++ b/tools/tests/test_native_inputs.py @@ -0,0 +1,389 @@ +#!/usr/bin/env python3 +"""Tests for tools/scripts/native-inputs.py (the keys) and tools/tests/check-native-inputs.py (the +check that holds them to what the jobs read). + +Owners: how OWNERS places a file. Commands, Yaml and Mentions: how the check reads workflow steps. +Each case is a way of running a file or make that, read wrong, would hide a read from the check. +Paths and Contexts: how the check finds the paths a file names and the values that change between +runs. + +Goals: what the keys must do, checked on throwaway commits of the working tree, and that the check +catches a job reading what its key leaves out. They need cargo (and make, for the jobs that run +it), so they are skipped without it; Static Checks has both. +""" +import importlib.util +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +sys.dont_write_bytecode = True # no __pycache__ beside the scripts +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +check = load("check_native_inputs", os.path.join(HERE, "check-native-inputs.py")) +ni = check.ni + + +def step(*lines): + return [" - " + lines[0], *(" " + line for line in lines[1:])] + + +def ran(*lines): + _, files, guesses, make = check.commands(step(*lines), "test") + return files, [path for _, path in guesses], make + + +class Owners(unittest.TestCase): + def test_a_file_no_rule_places_is_read_by_every_artifact(self): + self.assertEqual(ni.owners("tools/helpers/new.sh"), ni.EVERYONE) + self.assertEqual(ni.owners("packages/canvas/src-native/new-platform/x.c"), ni.MOBILE) + + def test_the_last_matching_rule_decides(self): + self.assertEqual(ni.owners("packages/canvas/index.ts"), ni.NONE) + self.assertEqual(ni.owners("packages/canvas/src-native/canvas-ios/x.ts"), ("canvas-ios",)) + self.assertEqual(ni.owners("packages/canvas/platforms/ios/src/cpp/x.h"), ("canvas-android",)) + self.assertEqual(ni.owners("packages/canvas-media/platforms/linux/lib/x64/x.node"), ni.LINUX) + + def test_a_rule_matches_whole_path_segments(self): + self.assertTrue(ni.matches("tools/demo", "tools/demo/x.png")) + self.assertFalse(ni.matches("tools/demo", "tools/demos/x.png")) + self.assertTrue(ni.matches("packages/*/platforms", "packages/canvas/platforms/android/x.aar")) + + +class Commands(unittest.TestCase): + def test_interpreters_and_their_options(self): + self.assertEqual(ran("run: bash -e tools/scripts/x.sh")[0], {"tools/scripts/x.sh"}) + self.assertEqual(ran("run: bash -o pipefail tools/scripts/x.sh")[0], {"tools/scripts/x.sh"}) + self.assertEqual(ran("run: py -3 tools/x.py")[0], {"tools/x.py"}) + self.assertEqual(ran("run: pwsh -File tools\\scripts\\x.ps1")[0], {"tools/scripts/x.ps1"}) + self.assertEqual(ran("run: bash -c './tools/scripts/x.sh'")[0], {"tools/scripts/x.sh"}) + self.assertEqual(ran("run: bash -c 'echo hi'")[0], set()) + + def test_wrappers_and_their_options(self): + self.assertEqual(ran("run: sudo -E ./tools/x.sh")[0], {"tools/x.sh"}) + self.assertEqual(ran("run: timeout -s KILL 5m ./tools/x.sh")[0], {"tools/x.sh"}) + self.assertEqual(ran("run: env -u X FOO=1 ./tools/x.sh")[0], {"tools/x.sh"}) + self.assertEqual(ran("run: nice -n 10 make android")[2], (["android"], [])) + self.assertEqual(ran("run: arch -arm64 make ios")[2], (["ios"], [])) + for lines in (["run: sudo apt-get install -y make cmake"], ["run: command -v make"], ["run: which make"]): + with self.subTest(lines=lines): + self.assertEqual(ran(*lines)[2], None) + + def test_workspace_prefixes(self): + self.assertEqual(ran('run: bash "$GITHUB_WORKSPACE/tools/x.sh"')[0], {"tools/x.sh"}) + self.assertEqual(ran("run: ${{ github.workspace }}/tools/x.sh")[0], {"tools/x.sh"}) + + def test_working_directory_anywhere_in_the_step(self): + self.assertEqual(ran("working-directory: tools/scripts", "run: sh x.sh")[0], {"tools/scripts/x.sh"}) + self.assertEqual(ran("run: \"./x.sh\"", "working-directory: tools/scripts")[0], {"tools/scripts/x.sh"}) + + def test_paths_run_directly(self): + self.assertEqual(ran("run: ci/foo.sh")[0], {"ci/foo.sh"}) + self.assertEqual(ran("run: |", " bash \\", " ci/foo.sh")[0], {"ci/foo.sh"}) + self.assertEqual(ran("run: if true; then ./ci/foo.sh; fi")[0], {"ci/foo.sh"}) + + def test_quoting_escapes_heredocs_and_redirections(self): + self.assertEqual(ran("run: LLVM='C:\\Program Files\\LLVM' && echo \"a; b | c\"")[0], set()) + self.assertEqual(ran("run: bash \"tools/my scripts/x.sh\" 'a;b'")[0], {"tools/my scripts/x.sh"}) + self.assertEqual(ran("run: \"C:/Program Files/x/run.sh\"")[0], set()) + self.assertEqual(ran("run: |", " echo \"a \\\" b\"", " bash tools/x.sh")[0], {"tools/x.sh"}) + self.assertEqual(ran("run: |", " cat > f <<'EOF'", " it's", " EOF", " make android")[2], (["android"], [])) + self.assertEqual(ran("run: make android 2>&1 | tee build.log")[2], (["android"], [])) + + def test_a_script_without_extension_must_exist(self): + self.assertEqual(ran("working-directory: tools", "run: bash build")[1], ["tools/build"]) + + def test_refusals(self): + for lines in (["run: cd tools && ./x.sh"], ["run: python -m tools.x"], ["run: ./../x.sh"], + ["run: echo \"unclosed"], ["run: npm run build.canvas.ios"], ["run: |", " cat < stamp\n') + self.assertTrue(any("GITHUB_SHA" in p for p in self.problems("canvas-windows", rev))) + + def test_check_holds_the_claims_about_fixtures(self): + rule = "apps/demo/src/assets/file-assets/audio" + saved = list(ni.OWNERS) + ni.OWNERS[:] = [r for r in ni.OWNERS if r[0] != rule] + ni.owners.cache_clear() + try: + self.assertEqual(len(ni.OWNERS), len(saved) - 1) + self.assertTrue(any(rule in p for p in self.problems("canvas-windows", self.base))) + finally: + ni.OWNERS[:] = saved + ni.owners.cache_clear() + + @unittest.skipUnless(shutil.which("make"), "needs make") + def test_check_holds_the_claims_about_build_files(self): + rule = "packages/canvas/platforms/ios/src/cpp" + saved = list(ni.OWNERS) + ni.OWNERS[:] = [r for r in ni.OWNERS if r[0] != rule] + ni.owners.cache_clear() + try: + self.assertTrue(any(rule in p for p in self.problems("canvas-android", self.base))) + finally: + ni.OWNERS[:] = saved + ni.owners.cache_clear() + + def test_the_wiring(self): + guarded = " - name: Build Rust libraries\n if: steps.native.outputs.hit != 'true'\n run: make android" + for name, new in (("unguarded", " - name: Build Rust libraries\n run: make android"), + ("|| guard", guarded.replace("!= 'true'", "!= 'true' || always()")), + ("run context", guarded.replace("run: make android", "run: echo ${{ github.sha }} && make android"))): + with self.subTest(name=name): + self.assertRaises(ni.Failure, check.check_wiring, self.edit(ni.BUILD_NATIVE, guarded, new)) + self.assertRaises(ni.Failure, check.check_wiring, + self.edit(ni.BUILD_NATIVE, " variant: ${{ toJSON(matrix) }}\n", "")) + check.check_wiring(self.base) + + def test_the_wiring_of_an_artifact_built_in_parts(self): + gate = " needs: canvas-ios-cache\n if: needs.canvas-ios-cache.outputs.hit != 'true'\n" + for name, old, new in (("ungated part", gate, " needs: canvas-ios-cache\n"), + ("|| gate", gate, gate.replace("!= 'true'", "!= 'true' || always()")), + ("own key", " key: ${{ needs.canvas-ios-cache.outputs.key }}\n", ""), + ("no lookup", " lookup-only: 'true'\n", "")): + with self.subTest(name=name): + self.assertRaises(ni.Failure, check.check_wiring, self.edit(ni.BUILD_NATIVE, old, new)) + self.assertIn(f"{ni.BUILD_NATIVE}#canvas-apple", ni.key_inputs("canvas-ios", self.base)) + + +if __name__ == "__main__": + sys.exit(unittest.main(verbosity=1)) From dc7f36f2f2fa9b5cc0f9b92f9d9cb82dab12473d Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:40:31 +0800 Subject: [PATCH 02/12] ci: restore multi-job outputs in their first job; widen the key scan GitHub evaluates expressions in an action's input descriptions, so the native-cache action did not load on any runner. The check now fails on an expression in any local action's metadata. An xcframework's first job now restores it, uploads it on a hit and skips the jobs that build it, so a cache entry lost between a lookup and a restore can no longer fail the run, and a hit takes one macOS runner instead of two. On a miss, the last job saves it under the first job's key. That job must need every part, and no job of the output may use always(), cancelled() or failure(), so a failed leg cannot ship a partial xcframework. The key scan now resolves paths from any dir above the file when they go up or start at an unknown variable (CMAKE_CURRENT_SOURCE_DIR, CARGO_MANIFEST_DIR with "/../x", Xcode group paths, Gradle's rootDir), flags crate dirs outside the closure, strips comments by each file's syntax, skips prose, expands matrix values to the values the strategy lists, and fails on a keyed text file too large to scan. The Makefile check also refuses $(VAR:a=b), $V and variables only a recipe sets. The Cargo resolution input now names the dependency fields it hashes and includes each member's features. The Apple builds key only their binary dirs under platforms/ios, and the JavaScript-only packages are placed. --- .github/actions/native-cache/action.yml | 29 +- .github/workflows/build-native.yml | 40 ++- .github/workflows/pull-request.yml | 6 +- tools/scripts/native-inputs.py | 26 +- tools/tests/check-native-inputs.py | 342 ++++++++++++++++-------- tools/tests/test_native_inputs.py | 47 +++- 6 files changed, 335 insertions(+), 155 deletions(-) diff --git a/.github/actions/native-cache/action.yml b/.github/actions/native-cache/action.yml index 7f0c3caa7..05200bec6 100644 --- a/.github/actions/native-cache/action.yml +++ b/.github/actions/native-cache/action.yml @@ -7,9 +7,9 @@ description: > scope of the ref that ran it, so pull requests can restore master's entries. With NATIVE_CACHE_FRESH=true (the release) it neither restores nor saves, and the job builds. - An output built by several jobs is looked up first, in a job of its own (`lookup-only`), whose - `hit` skips the jobs that build its parts and whose `key` the job that restores it passes back, - so both use the same week. + An output built by several jobs is restored first, in a job of its own (`restore-only`) that + uploads it on a hit and skips the other jobs. On a miss they build it, and the last of them saves + it under the `key` the first passes on, so both use the same week. inputs: artifact: @@ -19,24 +19,24 @@ inputs: description: The finished output, the same path the job uploads required: true variant: - description: "In a matrix job, `${{ toJSON(matrix) }}`: every leg gets its own key" + description: In a matrix job, the matrix as JSON (toJSON of matrix), so every leg gets its own key required: false default: '' - lookup-only: - description: "'true' to only tell whether the output is cached, without restoring or saving it" + restore-only: + description: "'true' in the first job of an output built by several jobs: restore it, but leave the saving to the job that builds it" required: false default: 'false' key: - description: The key a lookup job computed for this output in the same run + description: The key the first job of an output built by several jobs computed, in the same run required: false default: '' outputs: hit: - description: "'true' when the output is cached (and, unless lookup-only, restored), so the build can be skipped" - value: ${{ steps.cache.outputs.cache-hit || steps.lookup.outputs.cache-hit }} + description: "'true' when the output was restored and the build can be skipped" + value: ${{ steps.cache.outputs.cache-hit || steps.restore.outputs.cache-hit }} key: - description: The key, for the job that restores the output after a lookup + description: The key, for the jobs that build the output after a miss value: ${{ inputs.key || steps.key.outputs.key }} runs: @@ -67,17 +67,16 @@ runs: # Exact keys only: an output built from other inputs is never the right one. - name: Restore id: cache - if: env.NATIVE_CACHE_FRESH != 'true' && inputs.lookup-only != 'true' + if: env.NATIVE_CACHE_FRESH != 'true' && inputs.restore-only != 'true' uses: actions/cache@v4 with: path: ${{ inputs.path }} key: ${{ inputs.key || steps.key.outputs.key }} - - name: Look up - id: lookup - if: env.NATIVE_CACHE_FRESH != 'true' && inputs.lookup-only == 'true' + - name: Restore without saving + id: restore + if: env.NATIVE_CACHE_FRESH != 'true' && inputs.restore-only == 'true' uses: actions/cache/restore@v4 with: path: ${{ inputs.path }} key: ${{ steps.key.outputs.key }} - lookup-only: true diff --git a/.github/workflows/build-native.yml b/.github/workflows/build-native.yml index 02db29cd1..605a20ea3 100644 --- a/.github/workflows/build-native.yml +++ b/.github/workflows/build-native.yml @@ -46,10 +46,10 @@ # is built from (tools/scripts/native-inputs.py says what that covers). On a hit it skips its build # and uploads the restored output, so a change rebuilds only the jobs that depend on it: a crate # change rebuilds every platform that links the crate, a Windows script change only the Windows -# jobs, and a TypeScript change nothing. An output built by several jobs (the Apple xcframeworks) -# is looked up first, so a hit skips the jobs that build its parts. A job that builds Skia also -# keeps Skia's built libraries per target in .github/actions/skia-cache, saved only by pushes to -# master. +# jobs, and a TypeScript change nothing. An output built by several jobs (the Apple xcframeworks) is +# restored by a job of its own, which on a hit uploads it and skips the jobs that build it. A job +# that builds Skia also keeps Skia's built libraries per target in .github/actions/skia-cache, saved +# only by pushes to master. name: Build Native permissions: @@ -112,10 +112,12 @@ jobs: path: packages/canvas/platforms/android/canvas-release.aar if-no-files-found: error - # A hit for the xcframework skips the per-platform jobs. The lookup runs on macOS, as the restore - # does, so both get the same cache version. + # The xcframework when nothing it is built from has changed: a hit uploads it here and skips the + # per-platform jobs and canvas-ios, so a lost cache entry cannot fail the run between them. A miss + # leaves canvas-ios to save it under this job's key. On macOS, as canvas-ios, for the same cache + # version. canvas-ios-cache: - name: Canvas xcframework cache lookup + name: Canvas xcframework (cached) runs-on: macos-15 outputs: hit: ${{ steps.native.outputs.hit }} @@ -127,7 +129,13 @@ jobs: with: artifact: canvas-ios path: canvas-ios.tar.gz - lookup-only: 'true' + restore-only: 'true' + - uses: actions/upload-artifact@v4 + if: steps.native.outputs.hit == 'true' + with: + name: canvas-ios + path: canvas-ios.tar.gz + if-no-files-found: error # One runner per platform: its Rust targets, then its framework slices. The Xcode pre-build # phase reruns cargo for each slice, so the slices are built in the job that owns the target dir. @@ -172,7 +180,7 @@ jobs: canvas-ios: name: Canvas xcframework needs: [canvas-ios-cache, canvas-apple] - if: ${{ !cancelled() && needs.canvas-ios-cache.result == 'success' && contains(fromJSON('["success","skipped"]'), needs.canvas-apple.result) }} + if: needs.canvas-ios-cache.outputs.hit != 'true' runs-on: macos-15 steps: - uses: actions/checkout@v4 @@ -258,9 +266,9 @@ jobs: path: packages/canvas-svg/platforms/android/canvassvg-release.aar if-no-files-found: error - # As canvas-ios: a hit for the xcframework skips the per-platform jobs. + # As canvas-ios-cache: a hit uploads the xcframework and skips the jobs that build it. canvas-svg-ios-cache: - name: Canvas SVG xcframework cache lookup + name: Canvas SVG xcframework (cached) runs-on: macos-15 outputs: hit: ${{ steps.native.outputs.hit }} @@ -272,7 +280,13 @@ jobs: with: artifact: canvas-svg-ios path: canvas-svg-ios.tar.gz - lookup-only: 'true' + restore-only: 'true' + - uses: actions/upload-artifact@v4 + if: steps.native.outputs.hit == 'true' + with: + name: canvas-svg-ios + path: canvas-svg-ios.tar.gz + if-no-files-found: error canvas-svg-apple: name: Canvas SVG ${{ matrix.platform }} @@ -312,7 +326,7 @@ jobs: canvas-svg-ios: name: Canvas SVG xcframework needs: [canvas-svg-ios-cache, canvas-svg-apple] - if: ${{ !cancelled() && needs.canvas-svg-ios-cache.result == 'success' && contains(fromJSON('["success","skipped"]'), needs.canvas-svg-apple.result) }} + if: needs.canvas-svg-ios-cache.outputs.hit != 'true' runs-on: macos-15 steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 8c7ef2756..264d45f80 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -25,9 +25,9 @@ concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - # Fast, dependency-free guards. These run first because they catch the class - # of regression that merges introduce silently -- see - # tools/tests/check-v8-bridge-invariants.py. + # Guards for the class of regression that merges introduce silently (see + # tools/tests/check-v8-bridge-invariants.py), on one Linux runner in a few + # minutes; the native cache check needs the runner's cargo and make. static-checks: name: Static Checks runs-on: ubuntu-22.04 diff --git a/tools/scripts/native-inputs.py b/tools/scripts/native-inputs.py index c69b7ab9d..2be2166b6 100644 --- a/tools/scripts/native-inputs.py +++ b/tools/scripts/native-inputs.py @@ -112,14 +112,16 @@ def apple(artifact, parts, crate): "copy-android copy-android-libs busy-trace busy-bench build-headers"), ] # The package dirs each build reads: its native sources and the platform dir it writes its output -# to (with the package's app-side files there). +# to (with the package's app-side files there). On Apple, only the binary's dir: the apps' pods +# compile platforms/ios/src, and no framework build reads it. PACKAGE_DIRS = { "canvas-android": ["packages/canvas/src-native/canvas-android", "packages/canvas/platforms/android"], - "canvas-ios": ["packages/canvas/src-native/canvas-ios", "packages/canvas/platforms/ios"], + "canvas-ios": ["packages/canvas/src-native/canvas-ios", "packages/canvas/platforms/ios/CanvasNativeBinary"], "canvas-svg-android": ["packages/canvas-svg/src-native/android", "packages/canvas-svg/platforms/android"], - "canvas-svg-ios": ["packages/canvas-svg/src-native/ios", "packages/canvas-svg/platforms/ios"], + "canvas-svg-ios": ["packages/canvas-svg/src-native/ios", "packages/canvas-svg/platforms/ios/CanvasSVGBinary"], "audio-context-android": ["packages/audio-context/src-native/android", "packages/audio-context/platforms/android"], - "audio-context-ios": ["packages/audio-context/src-native/ios", "packages/audio-context/platforms/ios"], + "audio-context-ios": ["packages/audio-context/src-native/ios", + "packages/audio-context/platforms/ios/AudioContextNativeBinary"], "canvas-windows": ["packages/canvas/platforms/windows"], "canvas-svg-windows": ["packages/canvas-svg/platforms/windows"], "audio-context-windows": ["packages/audio-context/platforms/windows"], @@ -139,7 +141,8 @@ def apple(artifact, parts, crate): ("tools/assets", NONE), ("tools/schematics", NONE), ("tools/tests", NONE), ("tools/workspace-scripts.js", NONE), ("tools/patches", NONE), ("packages/.gitkeep", NONE), *((name, NONE) for name in (".editorconfig", ".eslintignore", ".gitignore", ".husky", ".npmrc", ".npsrc", - ".nxignore", ".prettierignore", ".prettierrc", ".travis.yml", ".vscode", "LICENSE")), + ".nxignore", ".prettierignore", ".prettierrc", ".travis.yml", ".vscode", ".yarn", + ".yarnrc.yml", "LICENSE")), # Only audio-context-android checks out a submodule (Oboe). (".gitmodules", ("audio-context-android",)), # Only Apple's builds read Swift packages and pods, which name V8's headers too. @@ -151,8 +154,9 @@ def apple(artifact, parts, crate): # A package's platform dirs hold the files apps build from and the committed outputs; the # builds read none but their own output's (PACKAGE_DIRS). ("packages/*/src-native", MOBILE), ("packages/*/platforms", NONE), - # Its native code ships committed (async-release.aar); no job builds it. + # Its native code ships committed (async-release.aar); no job builds it. The others are JavaScript. ("packages/canvas-polyfill", NONE), + *((f"packages/canvas-{name}", NONE) for name in ("babylon", "chartjs", "phaser", "phaser-ce", "pixi", "three")), # No job runs it; the Node-API suites are under the crates. ("packages/canvas-gamepad/__test__", NONE), *((d, (artifact,)) for artifact, dirs in PACKAGE_DIRS.items() for d in dirs), @@ -167,6 +171,9 @@ def apple(artifact, parts, crate): ] RUST_ROOT = re.compile(r"^(Cargo\.toml|Cargo\.lock|rust-toolchain(\.toml)?|\.cargo/.*)$") +# What cargo metadata says of a dependency that can change the versions resolved. +RESOLVES = ("name", "req", "source", "registry", "kind", "target", "optional", "uses_default_features", "features", + "rename") LOCAL_USE = re.compile(r"^\s*(?:-\s+)?uses:\s*['\"]?\./([^\s'\"@#]+)") COMMENT = r"(?:\s+#.*)?" @@ -378,9 +385,10 @@ def rel(path): member = rel(posixpath.dirname(package["manifest_path"].replace("\\", "/"))) deps[member] = [rel(dep["path"]) for dep in package["dependencies"] if dep.get("path")] names[package["name"]] = member - declared = [{k: v for k, v in dep.items() if k != "path"} for dep in package["dependencies"]] - requirements[member] = {"rust_version": package.get("rust_version"), - "dependencies": sorted(declared, key=lambda d: json.dumps(d, sort_keys=True))} + # Named fields, so a cargo that reports more of them does not move every key. + declared = [[dep.get(k) for k in RESOLVES] for dep in package["dependencies"]] + requirements[member] = {"rust_version": package.get("rust_version"), "features": package.get("features"), + "dependencies": sorted(declared, key=json.dumps)} return deps, names, crate_dirs, requirements diff --git a/tools/tests/check-native-inputs.py b/tools/tests/check-native-inputs.py index a1e6c3e06..a66c03b3b 100644 --- a/tools/tests/check-native-inputs.py +++ b/tools/tests/check-native-inputs.py @@ -22,17 +22,21 @@ third-party builds in OWN_MAKE) or sources a computed path, a local action without action.yml, a workflow key after `jobs:`, a YAML anchor or alias, or a workflow- or job-wide working-directory. -Scanning the key: every text file in the key (up to 2 MB; the larger ones here are binaries) but the -workflows, actions and Makefile, and the step and job-key text the first pass reads, are searched for -paths that lead out of the key. A path counts relative to the repo or to the file's dir; after a -variable the file sets (`set(DIR ...)`, `DIR=...`), with each of its values; after any other -variable, from either place; with a glob or another variable standing for one path segment, or for -the dir it is in when that matches nothing; given as the segments of a join() or resolve() call; -and naming a dir, for every file under it. Comments and the values variables are set to are not -paths; a path made with a matrix value is not checked, since the legs of one job can be different -artifacts (each leg's values are in its key); and crates' tests, benches and examples count only -for the jobs in CARGO_TESTS, which run `cargo test`. This pass holds the claims about build files, -such as the C++ the Android CMake builds compile from the iOS package dir. +Scanning the key: every text file in the key but prose (docs, notices, git's own files), the +workflows, actions and Makefile, and the step and job-key text the first pass reads, are searched +for paths that lead out of the key. A path counts relative to the repo or to the file's dir, and +when it goes up (`..`), from any dir above the file; after a variable the file sets (`set(DIR +...)`, `DIR=...`), with each of its values; after any other variable (`${CMAKE_CURRENT_SOURCE_DIR}`, +`env!("CARGO_MANIFEST_DIR")` with `"/../x"`), from any of those dirs, with or without the `..` +after it; with a glob or another variable (a matrix value too) standing for one path segment, or +for the dir it is in when that matches nothing; given as the segments of a join() or resolve() +call; and naming a dir, for every file under it, or a crate dir outside the closure (but in a +Cargo.toml, which cargo metadata reads). Comments, by each kind of file's syntax, and the values +variables are set to are not paths. In a job whose legs build different artifacts, a path made with +a matrix value counts when no artifact of the job reads it. Crates' tests, benches and examples +count only for the jobs in CARGO_TESTS, which run `cargo test`. A file in the key over 2 MB must be +of a binary type (BINARY). This pass holds the claims about build files, such as the C++ the +Android CMake builds compile from the iOS package dir. A path a file names but its job does not read there (one it writes, say) is listed in NOT_READ with the reason, for both passes. @@ -44,15 +48,15 @@ first pass reads. And the wiring: each job that uploads an artifact in build-native.yml is one of an artifact's, and -one job of each artifact restores it: a native-cache step with `id: native` right after the +each artifact's first job restores it: a native-cache step with `id: native` right after the checkout, for its own artifact and the upload's path, with `variant: ${{ toJSON(matrix) }}` in a matrix job, and every later step but the upload skipped on a hit (its `if:` is `steps.native.outputs.hit != 'true'`, or that && more, with no ||). An artifact built by several -jobs (the xcframeworks) also has a lookup job, which is the checkout and the step with -`lookup-only: 'true'` and has its `hit` and `key` as outputs; each other job that builds a part of -it needs the lookup and has `if: needs..outputs.hit != 'true'` (or that && more, with no -||), and the restore passes `key: ${{ needs..outputs.key }}`, so both use the same week. -For the reader, a make target made of a matrix value counts once per value the strategy lists. +jobs (the xcframeworks) has a first job that restores it with `restore-only: 'true'`, only uploads +it on a hit, and has the step's `hit` and `key` as outputs. Its other jobs need the first and have +`if: needs..outputs.hit != 'true'` (or that && more, with no ||), and the last of them +restores it as above, with `key: ${{ needs..outputs.key }}`, and saves it. For the reader, +a make target made of a matrix value counts once per value the strategy lists. Needs git, Python 3.8+, cargo and make. """ @@ -300,18 +304,49 @@ def is_absolute(token): def matrix_values(strategy): - """{key: [values]} of the matrix keys a job's strategy lists inline (`platform: [ios, tvos]`).""" - return {m.group(1): [v.strip().strip("'\"") for v in m.group(2).split(",")] - for m in (re.match(r"^\s+([\w-]+):\s*\[([^\]]*)\]\s*$", line) for line in strategy) if m} + """{key: [values]} of the values a job's strategy lists for each matrix key: `platform: [ios, + tvos]`, a list of scalars, a list of maps (`module.name`), and include's maps (their own keys).""" + lines = [l for l in strategy if l.strip()] + start = next((i for i, l in enumerate(lines) if re.match(r"^\s+matrix:\s*$", l)), None) + if start is None: + return {} + values, key, column, item = {}, None, None, None + for line in lines[start + 1:]: + if ni.indent(line) <= ni.indent(lines[start]): + break + column = column if column is not None else ni.indent(line) + m = re.match(r"^\s*(-\s+)?([\w-]+):\s*(.*?)\s*$", line) or re.match(r"^\s*(-\s+)()(.+?)\s*$", line) + if not m: + continue + dash, name, value = m.groups() + if ni.indent(line) == column and not dash: + key = name + if value.startswith("["): + values[key] = [v.strip().strip("'\"") for v in value.strip("[]").split(",") if v.strip()] + continue + if key is None: + continue + if dash and not name: + values.setdefault(key, []).append(value.strip("'\"")) + continue + field_key = name if key == "include" else f"{key}.{name}" + if value and not value.startswith(("[", "{")): + values.setdefault(field_key, []) + if value.strip("'\"") not in values[field_key]: + values[field_key].append(value.strip("'\"")) + return values def each_leg(script, values): """The script with each word that holds a matrix value the strategy lists written once per value, so `make ${{ matrix.platform }}` reads as one make of every leg's target.""" - def legs(m): - options = values.get(m.group(2)) - return " ".join(m.group(0).replace(m.group(1), v) for v in options) if options else m.group(0) - return re.sub(r"[^\s'\"]*(\$\{\{\s*matrix\.([\w-]+)\s*\}\})[^\s'\"]*", legs, script) + # Marked without the spaces `${{ }}` holds, so each mark stays inside its word. + script = re.sub(r"\$\{\{\s*matrix\.([\w.-]+)\s*\}\}", lambda m: f"\x03{m.group(1)}\x03", script) + for key, options in values.items(): + mark = f"\x03{key}\x03" + script = re.sub(r"[^\s'\"]*" + re.escape(mark) + r"[^\s'\"]*", + lambda m: " ".join(m.group(0).replace(mark, v) for v in options), script) + return re.sub(r"\x03([\w.-]+)\x03", lambda m: "${{ matrix." + m.group(1) + " }}", script) def commands(step, where, values=None): @@ -433,12 +468,14 @@ def make_environment(makefile, variables): sets (a function's own, `$(call f,x)`'s $(1) and $(foreach x,...)'s x, are set), and its `?=` defaults where they make a path.""" makefile = makefile.replace("$$", "") - set_here = set(re.findall(r"^\s*(?:export\s+|override\s+)?([A-Za-z_][\w.-]*)\s*(?::{1,3}=|\+=|\?=|=)", makefile, re.M)) + # Not a recipe's (tab-indented) shell assignment, which sets nothing for make. + set_here = set(re.findall(r"^(?!\t)[ ]*(?:export\s+|override\s+)?([A-Za-z_][\w.-]*)\s*(?::{1,3}=|\+=|\?=|=)", makefile, re.M)) set_here |= {v.split("=", 1)[0] for v in variables} | set(re.findall(r"\$\(foreach\s+([\w.-]+)\s*,", makefile)) defaults = set(re.findall(r"^\s*([A-Za-z_][\w.-]*)\s*\?=", makefile, re.M)) found = [] - for m in re.finditer(r"\$[({]([A-Za-z_][\w.-]*)(?=[)}])", makefile): - name = m.group(1) + # $(X), ${X}, $(X:a=b) and $X. + for m in re.finditer(r"\$[({]([A-Za-z_][\w.-]*)(?=[:)}])|\$([A-Za-z_])", makefile): + name = m.group(1) or m.group(2) if name not in set_here and name not in ("MAKE", "MAKEFLAGS", "MAKECMDGOALS", "SHELL"): found.append(name) for name in defaults: @@ -514,7 +551,7 @@ def take(step, step_where, scan, values=None): executed.add(p) reach(p, step_where, wd) if scan: - texts_read.append((step_where, text, wd)) + texts_read.append((step_where, each_leg(text, values or {}), wd)) for p in mentions(text, [wd], tree): reach(p, step_where, wd) guesses.extend(step_guesses) @@ -531,7 +568,7 @@ def take(step, step_where, scan, values=None): raise ni.Failure(f"{where}: job-wide working-directory: {line.strip()}") # A matrix names every leg's values, each leg reads its own, and its key has them (variant). matrix = sections(outside, 4, {"strategy"}) - texts_read.append((f"{where} job keys", "\n".join(l for l in outside if l not in matrix), "")) + texts_read.append((f"{where} job keys", each_leg("\n".join(l for l in outside if l not in matrix), matrix_values(matrix)), "")) for p in mentions("\n".join(outside), [], tree): reach(p, f"{where} job keys") for step in steps: @@ -618,9 +655,16 @@ def check_reads(artifact, rev): if not moves_cache(step): for context in varying(expressions([], [step]), in_action=True): problems.append(f"{artifact}: {manifest} uses {context}, which can change between runs that share a key") - entries = ni.tree_entries(rev) + # A matrix value stands for any leg's, so in a job whose legs build different artifacts (the + # variant keys each leg) a path made with one counts when no artifact of the job reads it. + entries, of_job = ni.tree_entries(rev), {} + for path, job_id in ni.jobs_of(artifact): + legs = [a for a in ni.ARTIFACTS if (path, job_id) in ni.jobs_of(a)] + filters = [ni.key_filter(a, rev) for a in legs] if len(legs) > 1 else [wanted] + of_job[f"{path}#{job_id}"] = lambda p, filters=filters: any(f(p) for f in filters) for where, text, wd in texts_read: - problems += crossings(artifact, rev, wanted, where, wd, names(text, wd, entries) - set(reads)) + problems += crossings(artifact, rev, of_job.get(where.split(" ")[0], wanted), where, wd, + names(code(text, "step.yml"), wd, entries) - set(reads)) return problems + scan(artifact, rev, wanted) @@ -648,14 +692,20 @@ def varying(found, in_action=False): def check_wiring(rev): """Each job that uploads an artifact in build-native.yml is one of an artifact's, and each - artifact's jobs cache it. One job restores it: a native-cache step with `id: native` right after - the checkout, for that artifact and the upload's path, `variant: ${{ toJSON(matrix) }}` in a - matrix job, and every later step but the upload skipped on a hit. An artifact built by several - jobs also has a lookup job (checkout, then the step with `lookup-only: 'true'`, whose `hit` and - `key` are the job's outputs); its other jobs need it and are skipped on its hit, and the restore - takes its key. No job of an artifact uses a value that changes from run to run where it could - change what is built.""" + artifact's jobs cache it. Its first job restores it: a native-cache step with `id: native` right + after the checkout, for that artifact and the upload's path, `variant: ${{ toJSON(matrix) }}` in + a matrix job, and every later step but the upload skipped on a hit. An artifact built by several + jobs is restored with `restore-only: 'true'` by a first job that only uploads it on a hit and has + the step's `hit` and `key` as outputs; its other jobs need that job and are skipped on its hit, + and the last of them restores it as above, under the first job's key, and saves it. No job of an + artifact uses a value that changes from run to run where it could change what is built. And no + local action's metadata holds `${{ }}` but in its outputs' values: the runner evaluates it there + and cannot load the action.""" problems, artifacts_of, parsed = [], {}, {} + for manifest in sorted(p for p in ni.tracked(rev) if re.match(r"^\.github/actions/[^/]+/action\.ya?ml$", p)): + for line in ni.show(rev, manifest).split("\nruns:")[0].split("\n"): + if "${{" in line and not re.match(r"^\s*value:", line): + problems.append(f"{manifest}: an expression in an action's metadata stops the runner loading it: {line.strip()}") for artifact in ni.ARTIFACTS: for job in ni.jobs_of(artifact): artifacts_of.setdefault(job, []).append(artifact) @@ -677,7 +727,7 @@ def check_wiring(rev): if path == ni.BUILD_NATIVE and (uploads or cache): problems.append(f"{where}: builds an artifact, but no entry in ARTIFACTS lists this job") continue - parsed[path, job_id] = (outside, cache) + parsed[path, job_id] = (where, outside, steps, cache, uploads) # Steps that only move caches, like the upload, do not change what is built; nor do the # header's and the job's keys other than these. builds = [s for s in steps if s is not cache and s not in uploads and not moves_cache(s)] @@ -693,60 +743,80 @@ def check_wiring(rev): problems.append(f"{where}: native-cache artifact '{artifact}' is not one of this job's entries") if any(not re.match(r"^actions/checkout@", field(s, "uses")) for s in steps[:steps.index(cache)]): problems.append(f"{where}: only the checkout may come before the native-cache step") - if field(cache, "lookup-only") == "true": - if steps[steps.index(cache) + 1:]: - problems.append(f"{where}: a lookup job ends with its lookup") - outputs = dict(m.groups() for m in (re.match(r"^\s+([\w-]+):\s*(.*?)\s*$", l) - for l in sections(outside, 4, {"outputs"})[1:]) if m) - for name in ("hit", "key"): - if re.sub(r"\s", "", outputs.get(name, "")) != f"${{{{steps.native.outputs.{name}}}}}": - problems.append(f"{where}: a lookup job's outputs are `{name}: ${{{{ steps.native.outputs.{name} }}}}`") - continue if any(re.match(r"^\s+matrix:", l) for l in outside) and re.sub(r"\s", "", field(cache, "variant")) != "${{toJSON(matrix)}}": problems.append(f"{where}: a matrix job passes `variant: ${{{{ toJSON(matrix) }}}}`") - for upload in uploads: - if field(upload, "path").rstrip("/") != field(cache, "path").rstrip("/"): - problems.append(f"{where}: uploads {field(upload, 'path')} but caches {field(cache, 'path')}") - for step in steps[steps.index(cache) + 1:]: - condition = bare(field(step, "if")) - if step in uploads: - if condition: - problems.append(f"{where}: the upload must run on a hit too") - elif not guarded(condition, GUARD): - problems.append(f"{where}: `{step[0].strip()}` runs on a hit (its `if:` must be " - f"{GUARD}, or that && more, with no ||)") for artifact in ni.ARTIFACTS: jobs = ni.jobs_of(artifact) if any(job not in parsed for job in jobs): continue - lookups = [job for job in jobs if parsed[job][1] and field(parsed[job][1], "lookup-only") == "true"] - restores = [job for job in jobs if parsed[job][1] and job not in lookups] - parts = [job for job in jobs if parsed[job][1] is None] - if len(restores) != 1: - problems.append(f"{artifact}: one of its jobs restores it with the native-cache step") - if not lookups and not parts: - if restores and field(parsed[restores[0]][1], "key"): - problems.append(f"{artifact}: its native-cache step computes its own key") + cached = [job for job in jobs if parsed[job][3] is not None] + firsts = [job for job in cached if not field(parsed[job][3], "key")] + if len(firsts) != 1: + problems.append(f"{artifact}: one of its jobs restores it under the key it computes") continue - if len(lookups) != 1: - problems.append(f"{artifact}: it is built by several jobs, so one of them looks it up (`lookup-only: 'true'`)") + first = firsts[0] + where, outside, steps, cache, uploads = parsed[first] + if len(jobs) == 1: + if field(cache, "restore-only"): + problems.append(f"{where}: an output built by one job is restored and saved there, without restore-only") + problems += restored(*parsed[first]) continue - lookup = lookups[0][1] + if field(cache, "restore-only") != "true": + problems.append(f"{where}: {artifact} is built by several jobs, so its first job passes `restore-only: 'true'`") + outputs = dict(m.groups() for m in (re.match(r"^\s+([\w-]+):\s*(.*?)\s*$", l) + for l in sections(outside, 4, {"outputs"})[1:]) if m) + for name in ("hit", "key"): + if re.sub(r"\s", "", outputs.get(name, "")) != f"${{{{steps.native.outputs.{name}}}}}": + problems.append(f"{where}: its outputs are `{name}: ${{{{ steps.native.outputs.{name} }}}}`") + for step in steps[steps.index(cache) + 1:]: + if step not in uploads or bare(field(step, "if")) != "steps.native.outputs.hit == 'true'": + problems.append(f"{where}: after the restore it only uploads, with `if: steps.native.outputs.hit == 'true'`") + elif field(step, "path").rstrip("/") != field(cache, "path").rstrip("/"): + problems.append(f"{where}: uploads {field(step, 'path')} but restores {field(cache, 'path')}") + lookup = first[1] gate = f"needs.{lookup}.outputs.hit != 'true'" - for path, job_id in parts: - outside = parsed[path, job_id][0] - if lookup not in needs(outside) or not guarded(bare(job_key(outside, "if")), gate): - problems.append(f"{path}#{job_id}: builds part of {artifact}, so it needs {lookup} and its `if:` " - f"is {gate}, or that && more, with no ||") - for path, job_id in restores: - outside, cache = parsed[path, job_id] - if lookup not in needs(outside) or re.sub(r"\s", "", field(cache, "key")) != f"${{{{needs.{lookup}.outputs.key}}}}": - problems.append(f"{path}#{job_id}: restores {artifact} under the key {lookup} looked up: it needs " - f"{lookup} and passes `key: ${{{{ needs.{lookup}.outputs.key }}}}`") + for job in jobs: + condition = bare(job_key(parsed[job][1], "if")) + # A status function would run the job after one it needs failed: building from a part + # that is missing, or on a hit. + if job != first and (lookup not in needs(parsed[job][1]) or not guarded(condition, gate) + or re.search(r"\b(always|cancelled|failure)\s*\(", condition)): + problems.append(f"{parsed[job][0]}: it builds {artifact}, so it needs {lookup} and its `if:` is " + f"{gate}, or that && more, with no || and no always(), cancelled() or failure()") + lasts = [job for job in cached if job != first] + if len(lasts) != 1: + problems.append(f"{artifact}: one of the jobs that build it restores it under {lookup}'s key, to save it") + continue + last_where, last_outside, _, last_cache, _ = parsed[lasts[0]] + missing = sorted(j for _, j in jobs if (_, j) != lasts[0] and j not in needs(last_outside)) + if missing: + problems.append(f"{last_where}: it saves {artifact}, so it needs every job that builds a part: {', '.join(missing)}") + for name, want in (("key", f"${{{{needs.{lookup}.outputs.key}}}}"), ("artifact", field(cache, "artifact")), + ("path", field(cache, "path")), ("restore-only", "")): + if re.sub(r"\s", "", field(last_cache, name)) != re.sub(r"\s", "", want): + problems.append(f"{last_where}: its native-cache step's {name} must be {want or 'unset'}") + problems += restored(*parsed[lasts[0]]) if problems: raise ni.Failure("\n ".join(["native-cache wiring:", *sorted(set(problems), key=problems.index)])) +def restored(where, outside, steps, cache, uploads): + """The problems of a job that restores an output and builds it on a miss: it uploads what it + caches, on a hit too, and skips every other step on a hit.""" + problems = [] + for step in steps[steps.index(cache) + 1:]: + condition = bare(field(step, "if")) + if step in uploads: + if field(step, "path").rstrip("/") != field(cache, "path").rstrip("/"): + problems.append(f"{where}: uploads {field(step, 'path')} but caches {field(cache, 'path')}") + if condition: + problems.append(f"{where}: the upload must run on a hit too") + elif not guarded(condition, GUARD): + problems.append(f"{where}: `{step[0].strip()}` runs on a hit (its `if:` must be " + f"{GUARD}, or that && more, with no ||)") + return problems + + def bare(condition): return re.sub(r"^\$\{\{\s*|\s*\}\}$", "", " ".join(condition.split())) @@ -778,6 +848,20 @@ def sections(lines, column, keys): return out +LIMIT = 2_000_000 +# Files no build reads as text over the limit: what a key holds beyond it must be one of these. +BINARY = (".node", ".aar", ".so", ".dll", ".dylib", ".a", ".lib", ".jar", ".zip", ".ogg", ".wav", ".mp3", ".mp4", + ".png", ".jpg", ".jpeg", ".webp", ".gif", ".hdr", ".exr", ".glb", ".ktx2", ".fbx", ".3mf", ".bin", ".ttf", + ".otf", ".woff", ".woff2") +# How each kind of file writes comments; prose and git's own files are not read by builds. +C_LIKE = (".rs", ".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".inl", ".m", ".mm", ".swift", ".kt", ".kts", + ".java", ".gradle", ".groovy", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".go", ".cs", ".pbxproj", ".json5") +HASH = (".sh", ".bash", ".zsh", ".py", ".cmake", ".toml", ".yml", ".yaml", ".rb", ".pl", ".properties", ".podspec", + ".ps1", ".mk", ".cfg", ".ini", ".conf") +HASH_NAMES = ("CMakeLists.txt", "Makefile", "Podfile", "Gemfile", "Dockerfile") +XML = (".xml", ".plist", ".props", ".targets", ".storyboard", ".xib", ".xcscheme", ".xcworkspacedata", ".html") +PROSE = (".md", ".markdown", ".rst", ".adoc", ".txt") +PROSE_NAMES = re.compile(r"^(LICENSE|NOTICE|THIRD_PARTY_NOTICES|AUTHORS|CHANGELOG)([.-].*)?$|^\.git(ignore|attributes|keep)$") COMMENT_LINE = re.compile(r"^\s*(#|//|/\*|\*|", " ", text, flags=re.S) + if ext in HASH or name in HASH_NAMES: + return re.sub(r"(?m)(^|\s)#.*$", r"\1", text) + return "\n".join(line for line in text.split("\n") if not COMMENT_LINE.match(line)) + + def expand(text, values): """The text with each variable the file sets replaced by each of its values in turn, and any - other variable by WILD (a matrix value by LEG).""" - text = MATRIX_VALUE.sub(LEG, text) + other variable (a matrix value too) by WILD.""" m = VARIABLE.search(text) if m is None: return [text] @@ -840,19 +942,29 @@ def expand(text, values): def resolve_token(token, here, entries): """The tracked files and dirs a path in a file can name: from the repo or the file's dir, with - WILD and globs standing for one segment, and from either after an unknown variable (with the - `..` after it, which leads from somewhere unknown). A computed name that matches nothing names - the dir it is in.""" - token = re.sub(r"^(" + WILD + r"/(\.\./)*)+", "", token).rstrip(".") - if token.startswith("/") or "//" in token or LEG in token: + WILD and globs standing for one segment. A path that goes up (`..`), or starts at a dir the file + does not name (an unknown variable, or `"/../x"` after env!("CARGO_MANIFEST_DIR") or the like), + may start from any dir above the file, and after an unknown dir, the `..` may lead anywhere. A + computed name that matches nothing names its dir.""" + if token.startswith("/.."): + token = WILD + token + unknown = token.startswith(WILD + "/") + token = re.sub(r"^(" + WILD + r"/)+", "", token).rstrip(".") + if token.startswith("/") or "//" in token: return set() segments = [s for s in token.split("/") if s] if not any(re.search(r"[A-Za-z]", s) and not re.search(WILDS, s) for s in segments): return set() + bases = ["", here] + if unknown or segments[0] == "..": + bases += [here.rsplit("/", n)[0] for n in range(1, here.count("/") + 1)] + forms = [segments] + if unknown and segments[0] == "..": + forms.append(segments[next(i for i, s in enumerate(segments) if s != ".."):]) found = set() - for base in ("", here): + for base, form in ((b, f) for b in bases for f in forms): try: - path = ni.norm(posixpath.join(base, *segments)) + path = ni.norm(posixpath.join(base, *form)) except ni.Failure: continue if not re.search(WILDS, path): @@ -870,14 +982,14 @@ def resolve_token(token, here, entries): def names(text, here, entries): - """The tracked files and dirs the text's paths name, from the repo or from here.""" + """The tracked files and dirs the text's paths name (see resolve_token).""" return set().union(*(resolve_token(token, here, entries) for token in path_tokens(text))) @functools.lru_cache(maxsize=None) def path_tokens(text): - """The paths the text names outside comments and the values it sets variables to, with the - variables it sets expanded.""" + """The paths the text names, but the values it sets variables to, with the variables it sets + expanded. The text is code: its comments already gone.""" values, found = {}, set() def define(name, value): @@ -887,8 +999,6 @@ def define(name, value): for v in expand(value.strip("'\""), values) if v not in values[name]] for line in text.split("\n"): - if COMMENT_LINE.match(line): - continue cmake = CMAKE_SET.match(line) if cmake: define(cmake.group(2), cmake.group(3) + ("/.." if cmake.group(1).lower() != "set" else "")) @@ -906,7 +1016,8 @@ def define(name, value): @functools.lru_cache(maxsize=None) def named_paths(rev, p): - return frozenset(names(texts(rev)[p], posixpath.dirname(p), ni.tree_entries(rev))) + text = code(texts(rev)[p], p) + return frozenset() if text is None else frozenset(names(text, posixpath.dirname(p), ni.tree_entries(rev))) @functools.lru_cache(maxsize=None) @@ -925,13 +1036,19 @@ def crate_of(rev, p): def crossings(artifact, rev, wanted, source, here, targets): - """The targets that source names and the artifact's key leaves out, but crate dirs (which name - crates), source itself and the dirs it is in, and NOT_READ's.""" + """The targets that source names and the artifact's key leaves out, but source itself and the + dirs it is in, and NOT_READ's. A crate dir counts when it is outside the closure, unless a + Cargo.toml names it (cargo metadata reads those).""" entries, under, problems = ni.tree_entries(rev), files_under(rev), [] crate_dirs, crates = ni.crate_meta(rev)[2], ni.closure(rev, ni.ARTIFACTS[artifact].get("crates", [])) for target in sorted(targets): - if (target in crate_dirs or target == source or target.startswith(".github/workflows/") - or here == target or here.startswith(target + "/") or not_read(source, target)): + if (target == source or target.startswith(".github/workflows/") or here == target + or here.startswith(target + "/") or not_read(source, target)): + continue + if target in crate_dirs: + if target not in crates and posixpath.basename(source) != "Cargo.toml": + problems.append(f"{artifact}: {source} names the crate {target}, which is outside its crates' " + f"closure; if its job does not read it there, add it to NOT_READ with the reason") continue left_out = [f for f in (under[target] if entries[target][0] == "tree" else [target]) if not wanted(f)] if left_out: @@ -945,10 +1062,13 @@ def crossings(artifact, rev, wanted, source, here, targets): def scan(artifact, rev, wanted): - """The paths that the text files in the artifact's key name and its key leaves out. The job - pass reads the workflows, actions and Makefile for what the job runs of them.""" + """The paths that the text files in the artifact's key name and its key leaves out, and the files + in it too large to read that are not binaries. The job pass reads the workflows, actions and + Makefile for what the job runs of them.""" tested = set(ni.ARTIFACTS[artifact].get("crates", [])) if artifact in CARGO_TESTS else set() - problems = [] + problems = [f"{artifact}: {p} is in its key but too large to scan for paths; if it is not text, add its " + f"type to BINARY" for p, (_, size) in sorted(blobs(rev).items()) + if size > LIMIT and wanted(p) and not p.lower().endswith(BINARY)] for p in sorted(texts(rev)): if p.startswith(".github/") or p == "Makefile" or not wanted(p): continue diff --git a/tools/tests/test_native_inputs.py b/tools/tests/test_native_inputs.py index 71168fa1f..106d4f908 100644 --- a/tools/tests/test_native_inputs.py +++ b/tools/tests/test_native_inputs.py @@ -134,6 +134,9 @@ def test_what_the_environment_can_change_in_the_makefile(self): self.assertEqual(check.make_environment("x:\n\t./$(S)\n", ["S=a.sh"]), []) self.assertEqual(check.make_environment( "T ?= nightly\nf = echo $(1)\nx:\n\tcargo +$(T) $(call f,a) $(foreach v,a b,$(v)) $$(HOME)\n", []), []) + for makefile in ("t:\n\tS=x.sh cargo test\nx:\n\t./$(S)\n", "x:\n\t./$(S:.sh=-2.sh)\n", "x:\n\t./$S\n"): + with self.subTest(makefile=makefile): + self.assertEqual(check.make_environment(makefile, []), ["S"]) class Yaml(unittest.TestCase): @@ -202,6 +205,14 @@ def test_relative_to_the_file_and_after_a_variable(self): self.assertEqual(named("set(DIR ../../platforms/ios/src/cpp)\nadd_library(x ${DIR}/Caches.cpp)", here), {cpp + "/Caches.cpp"}) self.assertEqual(named("include(${PROJECT_ROOT}/../../packages/canvas/platforms/ios/src/cpp)"), {cpp}) + def test_from_a_dir_above_the_file(self): + cpp = "packages/canvas/platforms/ios/src/cpp" + here = "packages/canvas/src-native/android" + self.assertEqual(named("include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../platforms/ios/src/cpp)", here), {cpp}) + self.assertEqual(named('include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../platforms/ios/src/cpp/Caches.cpp"))', here), + {cpp + "/Caches.cpp"}) + self.assertEqual(named('Path::new(root).join("../../platforms/ios/src/cpp")', here + "/src"), {cpp}) + def test_values_set_in_case_branches(self): text = " a) PKG=packages/canvas ;;\n b) PKG=tools/assets ;;\nesac\ncp $PKG/icons/a.png out" self.assertEqual(named(text), {"tools/assets/icons/a.png"}) @@ -215,9 +226,21 @@ def test_dirs_globs_and_computed_names(self): def test_a_path_given_as_segments(self): self.assertEqual(named("const a = path.join(root, 'apps', 'demo', 'audio');"), {"apps/demo/audio"}) - def test_comments_and_matrix_values_are_not_paths(self): - self.assertEqual(named("# see tools/assets\n// tools/assets"), set()) - self.assertEqual(named("cp packages/${{ matrix.name }}/platforms x"), set()) + def test_comments_by_the_kind_of_file(self): + self.assertEqual(named(check.code("x(); // mirrors tools/assets\n/* tools/assets */ y(\"tools/assets\");", "a.rs")), + {"tools/assets"}) + self.assertEqual(named(check.code("# tools/assets\necho x # tools/assets\nls ${#a}", "a.sh")), set()) + self.assertIsNone(check.code("see tools/assets", "packages/x/platforms/README.md")) + + def test_a_matrix_value_is_one_segment_or_each_listed_value(self): + self.assertEqual(named("cp packages/${{ matrix.name }}/platforms x"), {"packages/canvas/platforms"}) + self.assertEqual(check.each_leg("cp packages/${{ matrix.m.name }}/x/${{ matrix.arch }}", {"m.name": ["a"], "arch": ["x64", "arm64"]}), + "cp packages/a/x/x64 packages/a/x/arm64") + strategy = [" strategy:", " matrix:", " module:", " - name: canvas-svg", " crate: svg", + " - name: audio", " arch: [x64, arm64]", " include:", " - arch: x64", + " target: x86_64"] + self.assertEqual(check.matrix_values(strategy), {"module.name": ["canvas-svg", "audio"], "module.crate": ["svg"], + "arch": ["x64", "arm64"], "target": ["x86_64"]}) class Contexts(unittest.TestCase): @@ -372,18 +395,34 @@ def test_the_wiring(self): self.assertRaises(ni.Failure, check.check_wiring, self.edit(ni.BUILD_NATIVE, guarded, new)) self.assertRaises(ni.Failure, check.check_wiring, self.edit(ni.BUILD_NATIVE, " variant: ${{ toJSON(matrix) }}\n", "")) + # GitHub evaluates expressions in an action's input descriptions and fails to load it. + self.assertRaises(ni.Failure, check.check_wiring, self.edit( + f"{ni.CACHE_ACTION}/action.yml", " description: The job's entry", " description: ${{ inputs.x }} The job's entry")) check.check_wiring(self.base) def test_the_wiring_of_an_artifact_built_in_parts(self): gate = " needs: canvas-ios-cache\n if: needs.canvas-ios-cache.outputs.hit != 'true'\n" + combine = " needs: [canvas-ios-cache, canvas-apple]\n if: needs.canvas-ios-cache.outputs.hit != 'true'\n" for name, old, new in (("ungated part", gate, " needs: canvas-ios-cache\n"), ("|| gate", gate, gate.replace("!= 'true'", "!= 'true' || always()")), ("own key", " key: ${{ needs.canvas-ios-cache.outputs.key }}\n", ""), - ("no lookup", " lookup-only: 'true'\n", "")): + ("saving first job", " artifact: canvas-ios\n path: canvas-ios.tar.gz\n" + " restore-only: 'true'\n", + " artifact: canvas-ios\n path: canvas-ios.tar.gz\n"), + ("first job uploading on a miss", " if: steps.native.outputs.hit == 'true'\n" + " with:\n name: canvas-ios\n", + " with:\n name: canvas-ios\n"), + ("last job running after a failed part", combine, + combine.replace("'true'\n", "'true' && !cancelled()\n")), + ("last job not needing the parts", combine, combine.replace(", canvas-apple]", "]"))): with self.subTest(name=name): self.assertRaises(ni.Failure, check.check_wiring, self.edit(ni.BUILD_NATIVE, old, new)) self.assertIn(f"{ni.BUILD_NATIVE}#canvas-apple", ni.key_inputs("canvas-ios", self.base)) + def test_check_fails_a_build_file_naming_a_crate_outside_the_closure(self): + rev = self.commit("packages/audio-context/src-native/android/extra.gradle", 'cargo { module = "../../../../crates/canvas-core" }\n') + self.assertTrue(any("crates/canvas-core" in p for p in self.problems("audio-context-android", rev))) + if __name__ == "__main__": sys.exit(unittest.main(verbosity=1)) From a3b5b216a519a97ce9f9db70260cf8a61f557d88 Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:21:58 +0800 Subject: [PATCH 03/12] ci: read paths in strings, after cd and per leg; check every if and upload The key scan no longer takes a comment marker inside a string for a comment, so a glob such as "src/*/gen.rs" or '**/*.so' cannot hide the reads after it; Ruby's #{x} reads as a variable, and a kind of file whose comments are not known is scanned whole. It follows a script's cd, so a ../ path after one resolves. In a job whose legs build different outputs, only paths made with a matrix value count against any leg; every other path counts against the output's own key. The wiring check refuses a status function (success(), always(), cancelled(), failure()) in any if: of an output's jobs, requires each build-native.yml job that restores an output to upload it once under its artifact's name, and refuses expressions only in action descriptions. The Makefile check accepts a target's own variables and define blocks, and refuses a ?= default next to any path character. A matrix list written over several lines is refused, since its values could not be read. The repo's .github settings and JavaScript and CSS files belong to no output, nor do the build scripts only nx runs (build-ios.sh and the debug builds). Outputs without crates compute their key without cargo. --- tools/scripts/native-inputs.py | 30 ++-- tools/tests/check-native-inputs.py | 225 +++++++++++++++++++---------- tools/tests/test_native_inputs.py | 40 ++++- 3 files changed, 207 insertions(+), 88 deletions(-) diff --git a/tools/scripts/native-inputs.py b/tools/scripts/native-inputs.py index 2be2166b6..393a6c673 100644 --- a/tools/scripts/native-inputs.py +++ b/tools/scripts/native-inputs.py @@ -100,8 +100,8 @@ def apple(artifact, parts, crate): (("canvas-android",), "build-android"), (("canvas-svg-android",), "build-svg-android copy-svg-android"), (("canvas-android", "canvas-svg-android"), "build-android-v8-stub"), - (("canvas-ios",), "build-ios canvas-build canvas-build-debug"), - (("canvas-svg-ios",), "canvas-svg-build canvas-svg-build-debug"), + (("canvas-ios",), "canvas-build"), + (("canvas-svg-ios",), "canvas-svg-build"), (("audio-context-ios",), "audio-context-build"), (V8, "download-v8"), (WINDOWS, "build-napi download-angle"), @@ -109,7 +109,8 @@ def apple(artifact, parts, crate): # Release steps, which run on what the builds produced, the apps' download of the release's # frameworks (each release bumps its version), and the maintainers' scripts no job runs. (NONE, "place-native-artifacts release-ios-binaries download-ios-frameworks release repack android-build " - "copy-android copy-android-libs busy-trace busy-bench build-headers"), + "copy-android copy-android-libs busy-trace busy-bench build-headers build-ios canvas-build-debug " + "canvas-svg-build-debug"), ] # The package dirs each build reads: its native sources and the platform dir it writes its output # to (with the package's app-side files there). On Apple, only the binary's dir: the apps' pods @@ -137,7 +138,9 @@ def apple(artifact, parts, crate): OWNERS = [ # The npm packages' TypeScript, docs and manifests, the demos, the JS tooling, and the patches # maintainers apply by hand. - ("*.ts", NONE), ("*.md", NONE), ("*.json", NONE), ("apps", NONE), ("tools/demo", NONE), + *((f"*.{ext}", NONE) for ext in ("ts", "tsx", "js", "jsx", "mjs", "cjs", "css", "scss", "md", "json")), + # The repo's own GitHub settings (its workflows and actions are keyed by job). + (".github", NONE), ("apps", NONE), ("tools/demo", NONE), ("tools/assets", NONE), ("tools/schematics", NONE), ("tools/tests", NONE), ("tools/workspace-scripts.js", NONE), ("tools/patches", NONE), ("packages/.gitkeep", NONE), *((name, NONE) for name in (".editorconfig", ".eslintignore", ".gitignore", ".husky", ".npmrc", ".npsrc", @@ -345,6 +348,12 @@ def steps_of(text, key_column, where): return lines[:start] + lines[end:], steps +@functools.lru_cache(maxsize=None) +def crate_dirs(rev): + """Every dir with a Cargo.toml at rev, from git alone, so outputs without crates need no cargo.""" + return tuple(sorted(p[: -len("/Cargo.toml")] for p in tracked(rev) if p.endswith("/Cargo.toml"))) + + @functools.lru_cache(maxsize=None) def crate_meta(rev): """(deps, names, crate dirs, requirements) at rev: each workspace member's path dependencies and @@ -352,9 +361,8 @@ def crate_meta(rev): with a Cargo.toml, and what decides the versions cargo resolves for the workspace: each member's declared dependencies and rust-version.""" tree = tracked(rev) - crate_dirs = tuple(sorted(p[: -len("/Cargo.toml")] for p in tree if p.endswith("/Cargo.toml"))) root = sorted({"Cargo.toml", *(p for p in tree if RUST_ROOT.match(p))}) - archive = git("archive", "--format=tar", rev, "--", *root, *crate_dirs, binary=True) + archive = git("archive", "--format=tar", rev, "--", *root, *crate_dirs(rev), binary=True) with tempfile.TemporaryDirectory() as tmp: with tarfile.open(fileobj=io.BytesIO(archive)) as tar: if hasattr(tarfile, "data_filter"): @@ -389,15 +397,15 @@ def rel(path): declared = [[dep.get(k) for k in RESOLVES] for dep in package["dependencies"]] requirements[member] = {"rust_version": package.get("rust_version"), "features": package.get("features"), "dependencies": sorted(declared, key=json.dumps)} - return deps, names, crate_dirs, requirements + return deps, names, crate_dirs(rev), requirements def closure(rev, start): """The crate dirs an artifact building start reads: start, the members they reach by path, and every crate dir that is not a member. Nothing when start is empty.""" - deps, _, crate_dirs, _ = crate_meta(rev) if not start: return set() + deps, _, dirs, _ = crate_meta(rev) seen, queue = set(), list(start) while queue: crate = queue.pop() @@ -407,7 +415,7 @@ def closure(rev, start): raise Failure(f"{crate} is not a workspace member at {rev}") seen.add(crate) queue.extend(deps[crate]) - return seen | {d for d in crate_dirs if d not in deps} + return seen | {d for d in dirs if d not in deps} def used_actions(rev, text, where): @@ -433,7 +441,7 @@ def key_filter(artifact, rev): """Whether a tracked path is one of the artifact's inputs.""" actions = set().union(*(used_actions(rev, block, f"{path}#{job_id}") for path, job_id, _, block in job_blocks(artifact, rev))) crates = closure(rev, ARTIFACTS[artifact].get("crates", [])) - crate_dirs = sorted(crate_meta(rev)[2], key=len, reverse=True) + dirs = sorted(crate_dirs(rev), key=len, reverse=True) def wanted(p): if p.startswith(".github/workflows/"): @@ -442,7 +450,7 @@ def wanted(p): return True if p.startswith(".github/actions/"): return False - crate = next((d for d in crate_dirs if p.startswith(d + "/")), None) + crate = next((d for d in dirs if p.startswith(d + "/")), None) if crate is not None: return crate in crates if RUST_ROOT.match(p): diff --git a/tools/tests/check-native-inputs.py b/tools/tests/check-native-inputs.py index a66c03b3b..f58a6c2cf 100644 --- a/tools/tests/check-native-inputs.py +++ b/tools/tests/check-native-inputs.py @@ -310,7 +310,7 @@ def matrix_values(strategy): start = next((i for i, l in enumerate(lines) if re.match(r"^\s+matrix:\s*$", l)), None) if start is None: return {} - values, key, column, item = {}, None, None, None + values, key, column = {}, None, None for line in lines[start + 1:]: if ni.indent(line) <= ni.indent(lines[start]): break @@ -319,6 +319,8 @@ def matrix_values(strategy): if not m: continue dash, name, value = m.groups() + if value.startswith(("[", "{")) and not value.endswith(("]", "}")): + raise ni.Failure(f"write the matrix's `{name}:` on one line, so its values can be read: {line.strip()}") if ni.indent(line) == column and not dash: key = name if value.startswith("["): @@ -337,16 +339,35 @@ def matrix_values(strategy): return values +MATRIX = re.compile(r"\$\{\{\s*matrix\.([\w.-]+)\s*\}\}") +MATRIX_WORD = re.compile(r"[^\s'\"]*\x03[\w.-]+\x03[^\s'\"]*") + + +def marked(script): + """The script with each matrix value marked without the spaces `${{ }}` holds, so it stays in + its word.""" + return MATRIX.sub(lambda m: f"\x03{m.group(1)}\x03", script) + + +def unmarked(script): + return re.sub(r"\x03([\w.-]+)\x03", lambda m: "${{ matrix." + m.group(1) + " }}", script) + + +def apart(script): + """(the script without its words that hold a matrix value, and those words, a line each).""" + script = marked(script) + return unmarked(MATRIX_WORD.sub(" ", script)), unmarked("\n".join(MATRIX_WORD.findall(script))) + + def each_leg(script, values): """The script with each word that holds a matrix value the strategy lists written once per value, so `make ${{ matrix.platform }}` reads as one make of every leg's target.""" - # Marked without the spaces `${{ }}` holds, so each mark stays inside its word. - script = re.sub(r"\$\{\{\s*matrix\.([\w.-]+)\s*\}\}", lambda m: f"\x03{m.group(1)}\x03", script) + script = marked(script) for key, options in values.items(): mark = f"\x03{key}\x03" script = re.sub(r"[^\s'\"]*" + re.escape(mark) + r"[^\s'\"]*", lambda m: " ".join(m.group(0).replace(mark, v) for v in options), script) - return re.sub(r"\x03([\w.-]+)\x03", lambda m: "${{ matrix." + m.group(1) + " }}", script) + return unmarked(script) def commands(step, where, values=None): @@ -465,11 +486,14 @@ def make_command(args, moved, command, where): def make_environment(makefile, variables): """The variables a Makefile's commands can take from the environment: those it reads but never - sets (a function's own, `$(call f,x)`'s $(1) and $(foreach x,...)'s x, are set), and its `?=` - defaults where they make a path.""" + sets (a function's own, `$(call f,x)`'s $(1) and $(foreach x,...)'s x, are set, as are a + target's own, `t: X := y`, and `define X`), and its `?=` defaults where they make a path.""" makefile = makefile.replace("$$", "") # Not a recipe's (tab-indented) shell assignment, which sets nothing for make. - set_here = set(re.findall(r"^(?!\t)[ ]*(?:export\s+|override\s+)?([A-Za-z_][\w.-]*)\s*(?::{1,3}=|\+=|\?=|=)", makefile, re.M)) + assignment = r"(?:export[ \t]+|override[ \t]+)?([A-Za-z_][\w.-]*)[ \t]*(?::{1,3}=|\+=|\?=|=)" + set_here = set(re.findall(r"^(?!\t)[ ]*" + assignment, makefile, re.M)) + set_here |= set(re.findall(r"^(?!\t)[^:=#\n]+:(?!=)[ \t]*" + assignment, makefile, re.M)) + set_here |= set(re.findall(r"^define\s+([A-Za-z_][\w.-]*)", makefile, re.M)) set_here |= {v.split("=", 1)[0] for v in variables} | set(re.findall(r"\$\(foreach\s+([\w.-]+)\s*,", makefile)) defaults = set(re.findall(r"^\s*([A-Za-z_][\w.-]*)\s*\?=", makefile, re.M)) found = [] @@ -479,7 +503,8 @@ def make_environment(makefile, variables): if name not in set_here and name not in ("MAKE", "MAKEFLAGS", "MAKECMDGOALS", "SHELL"): found.append(name) for name in defaults: - if re.search(rf"/\$[({{]{re.escape(name)}[)}}]|\$[({{]{re.escape(name)}[)}}]/", makefile): + # Next to a path's characters: `dir/$(X)`, `$(X)/lib.a`, `$(X).mk`, `$(X)-out`. + if re.search(rf"[\w./-]\$[({{]{re.escape(name)}[)}}]|\$[({{]{re.escape(name)}[)}}][\w./-]", makefile): found.append(name) return sorted(set(found)) @@ -521,8 +546,8 @@ def named_crates(rev, corpus): def discover(artifact, rev): """What the artifact's job is seen to read: ({path: where it was found}, all the text read, its - actions' steps as [(manifest, step)], and the steps' and job keys' text whose mentions count, as - [(where, text, its working-directory)]).""" + actions' steps as [(manifest, step)], and the steps' and job keys' text whose paths count, as + [Read]).""" blocks = ni.job_blocks(artifact, rev) tree = ni.tracked(rev) reads, corpus, todo, guesses, makes, actions, executed, wd_of = {}, [b for *_, b in blocks], [], [], [], [], set(), {} @@ -538,7 +563,7 @@ def reach(p, how, wd=""): wd_of[p] = wd todo.append(p) - def take(step, step_where, scan, values=None): + def take(step, step_where, scan, values=None, job=None): wd, files, step_guesses, make = commands(step, step_where, values) text = "\n".join(step) corpus.append(text) @@ -551,7 +576,7 @@ def take(step, step_where, scan, values=None): executed.add(p) reach(p, step_where, wd) if scan: - texts_read.append((step_where, each_leg(text, values or {}), wd)) + texts_read.append(Read(step_where, job, text, wd, values or {})) for p in mentions(text, [wd], tree): reach(p, step_where, wd) guesses.extend(step_guesses) @@ -568,11 +593,12 @@ def take(step, step_where, scan, values=None): raise ni.Failure(f"{where}: job-wide working-directory: {line.strip()}") # A matrix names every leg's values, each leg reads its own, and its key has them (variant). matrix = sections(outside, 4, {"strategy"}) - texts_read.append((f"{where} job keys", each_leg("\n".join(l for l in outside if l not in matrix), matrix_values(matrix)), "")) + values = matrix_values(matrix) + texts_read.append(Read(f"{where} job keys", (path, job_id), "\n".join(l for l in outside if l not in matrix), "", values)) for p in mentions("\n".join(outside), [], tree): reach(p, f"{where} job keys") for step in steps: - take(step, where, True, matrix_values(matrix)) + take(step, where, True, values, (path, job_id)) for p in sorted(tree): if own(p) and p.endswith((".sh", ".bash")): reach(p, f"a script in {artifact}'s dirs") @@ -655,19 +681,30 @@ def check_reads(artifact, rev): if not moves_cache(step): for context in varying(expressions([], [step]), in_action=True): problems.append(f"{artifact}: {manifest} uses {context}, which can change between runs that share a key") - # A matrix value stands for any leg's, so in a job whose legs build different artifacts (the - # variant keys each leg) a path made with one counts when no artifact of the job reads it. - entries, of_job = ni.tree_entries(rev), {} - for path, job_id in ni.jobs_of(artifact): - legs = [a for a in ni.ARTIFACTS if (path, job_id) in ni.jobs_of(a)] - filters = [ni.key_filter(a, rev) for a in legs] if len(legs) > 1 else [wanted] - of_job[f"{path}#{job_id}"] = lambda p, filters=filters: any(f(p) for f in filters) - for where, text, wd in texts_read: - problems += crossings(artifact, rev, of_job.get(where.split(" ")[0], wanted), where, wd, - names(code(text, "step.yml"), wd, entries) - set(reads)) + # A path made with a matrix value is one leg's: in a job whose legs build different artifacts + # (the variant keys each leg), it counts when no artifact of the job reads it. Any other path + # counts against this artifact's key. + entries, cache = ni.tree_entries(rev), MATCHED.setdefault(rev, {}) + for read in texts_read: + legs = [a for a in ni.ARTIFACTS if read.job in ni.jobs_of(a)] if read.job else [artifact] + filters = [key_filter(a, rev) for a in legs] + plain, made = apart(read.text) + for text, wants in ((plain, wanted), (each_leg(made, read.values), lambda p: any(f(p) for f in filters))): + found = names(code(text, "step.yml"), read.wd, entries, cache) - set(reads) + problems += crossings(artifact, rev, wants, read.where, read.wd, found) return problems + scan(artifact, rev, wanted) +# Text the job pass read: where it is, its job (path, id) if it is a job's, its working-directory, +# and the values its job's matrix lists. +Read = collections.namedtuple("Read", "where job text wd values") + + +@functools.lru_cache(maxsize=None) +def key_filter(artifact, rev): + return ni.key_filter(artifact, rev) + + def moves_cache(step): return re.match(r"^actions/cache(/(restore|save))?@", field(step, "uses")) is not None @@ -698,14 +735,21 @@ def check_wiring(rev): jobs is restored with `restore-only: 'true'` by a first job that only uploads it on a hit and has the step's `hit` and `key` as outputs; its other jobs need that job and are skipped on its hit, and the last of them restores it as above, under the first job's key, and saves it. No job of an - artifact uses a value that changes from run to run where it could change what is built. And no - local action's metadata holds `${{ }}` but in its outputs' values: the runner evaluates it there - and cannot load the action.""" + artifact uses a value that changes from run to run where it could change what is built, nor a + status function (success(), always(), cancelled(), failure()) in an `if:`, which would run a + step or job after one it follows failed. Each build-native.yml job that restores an output + uploads it once, under its artifact's name. And no local action's descriptions hold `${{ }}`: + the runner evaluates them and cannot load the action.""" problems, artifacts_of, parsed = [], {}, {} for manifest in sorted(p for p in ni.tracked(rev) if re.match(r"^\.github/actions/[^/]+/action\.ya?ml$", p)): + column = None for line in ni.show(rev, manifest).split("\nruns:")[0].split("\n"): - if "${{" in line and not re.match(r"^\s*value:", line): - problems.append(f"{manifest}: an expression in an action's metadata stops the runner loading it: {line.strip()}") + if column is not None and line.strip() and ni.indent(line) <= column: + column = None + if re.match(r"^\s*description:", line): + column = ni.indent(line) + if column is not None and "${{" in line: + problems.append(f"{manifest}: an expression in an action's description stops the runner loading it: {line.strip()}") for artifact in ni.ARTIFACTS: for job in ni.jobs_of(artifact): artifacts_of.setdefault(job, []).append(artifact) @@ -734,6 +778,10 @@ def check_wiring(rev): job_settings = settings + sections(outside, 4, {"runs-on", "env", "defaults", "strategy", "container", "services"}) for context in varying(expressions(job_settings, builds)): problems.append(f"{where}: uses {context}, which can change between runs that share a key") + for condition in [job_key(outside, "if"), *(field(s, "if") for s in steps)]: + if STATUS.search(condition): + problems.append(f"{where}: `if: {condition.strip()}` holds a status function, which runs it after " + f"what it follows failed") if cache is None: continue if field(cache, "id") != "native": @@ -759,7 +807,7 @@ def check_wiring(rev): if len(jobs) == 1: if field(cache, "restore-only"): problems.append(f"{where}: an output built by one job is restored and saved there, without restore-only") - problems += restored(*parsed[first]) + problems += restored(*parsed[first], uploaded=first[0] == ni.BUILD_NATIVE) continue if field(cache, "restore-only") != "true": problems.append(f"{where}: {artifact} is built by several jobs, so its first job passes `restore-only: 'true'`") @@ -768,21 +816,16 @@ def check_wiring(rev): for name in ("hit", "key"): if re.sub(r"\s", "", outputs.get(name, "")) != f"${{{{steps.native.outputs.{name}}}}}": problems.append(f"{where}: its outputs are `{name}: ${{{{ steps.native.outputs.{name} }}}}`") - for step in steps[steps.index(cache) + 1:]: - if step not in uploads or bare(field(step, "if")) != "steps.native.outputs.hit == 'true'": - problems.append(f"{where}: after the restore it only uploads, with `if: steps.native.outputs.hit == 'true'`") - elif field(step, "path").rstrip("/") != field(cache, "path").rstrip("/"): - problems.append(f"{where}: uploads {field(step, 'path')} but restores {field(cache, 'path')}") + after = steps[steps.index(cache) + 1:] + if len(after) != 1 or after[0] not in uploads or bare(field(after[0], "if")) != "steps.native.outputs.hit == 'true'": + problems.append(f"{where}: after the restore it only uploads, once, with `if: steps.native.outputs.hit == 'true'`") + problems += uploaded_as(where, cache, after[:1]) lookup = first[1] gate = f"needs.{lookup}.outputs.hit != 'true'" for job in jobs: - condition = bare(job_key(parsed[job][1], "if")) - # A status function would run the job after one it needs failed: building from a part - # that is missing, or on a hit. - if job != first and (lookup not in needs(parsed[job][1]) or not guarded(condition, gate) - or re.search(r"\b(always|cancelled|failure)\s*\(", condition)): + if job != first and (lookup not in needs(parsed[job][1]) or not guarded(bare(job_key(parsed[job][1], "if")), gate)): problems.append(f"{parsed[job][0]}: it builds {artifact}, so it needs {lookup} and its `if:` is " - f"{gate}, or that && more, with no || and no always(), cancelled() or failure()") + f"{gate}, or that && more, with no ||") lasts = [job for job in cached if job != first] if len(lasts) != 1: problems.append(f"{artifact}: one of the jobs that build it restores it under {lookup}'s key, to save it") @@ -795,25 +838,39 @@ def check_wiring(rev): ("path", field(cache, "path")), ("restore-only", "")): if re.sub(r"\s", "", field(last_cache, name)) != re.sub(r"\s", "", want): problems.append(f"{last_where}: its native-cache step's {name} must be {want or 'unset'}") - problems += restored(*parsed[lasts[0]]) + problems += restored(*parsed[lasts[0]], uploaded=lasts[0][0] == ni.BUILD_NATIVE) if problems: raise ni.Failure("\n ".join(["native-cache wiring:", *sorted(set(problems), key=problems.index)])) -def restored(where, outside, steps, cache, uploads): - """The problems of a job that restores an output and builds it on a miss: it uploads what it - caches, on a hit too, and skips every other step on a hit.""" +STATUS = re.compile(r"\b(success|always|cancelled|failure)\s*\(") + + +def restored(where, outside, steps, cache, uploads, uploaded): + """The problems of a job that restores an output and builds it on a miss: it skips every step + but the upload on a hit, and when uploaded, uploads what it caches once, on a hit too.""" problems = [] for step in steps[steps.index(cache) + 1:]: - condition = bare(field(step, "if")) if step in uploads: - if field(step, "path").rstrip("/") != field(cache, "path").rstrip("/"): - problems.append(f"{where}: uploads {field(step, 'path')} but caches {field(cache, 'path')}") - if condition: + if bare(field(step, "if")): problems.append(f"{where}: the upload must run on a hit too") - elif not guarded(condition, GUARD): + elif not guarded(bare(field(step, "if")), GUARD): problems.append(f"{where}: `{step[0].strip()}` runs on a hit (its `if:` must be " f"{GUARD}, or that && more, with no ||)") + if uploaded and len(uploads) != 1: + problems.append(f"{where}: it uploads what it restores once") + return problems + uploaded_as(where, cache, uploads) + + +def uploaded_as(where, cache, uploads): + """The problems of uploads that are not the cached output under its artifact's name (with the + leg's suffix in a matrix job).""" + problems = [] + for upload in uploads: + if field(upload, "path").rstrip("/") != field(cache, "path").rstrip("/"): + problems.append(f"{where}: uploads {field(upload, 'path')} but caches {field(cache, 'path')}") + if not re.sub(r"\s", "", field(upload, "name")).startswith(re.sub(r"\s", "", field(cache, "artifact"))): + problems.append(f"{where}: uploads {field(upload, 'name')}, not {field(cache, 'artifact')}") return problems @@ -855,22 +912,30 @@ def sections(lines, column, keys): ".otf", ".woff", ".woff2") # How each kind of file writes comments; prose and git's own files are not read by builds. C_LIKE = (".rs", ".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".inl", ".m", ".mm", ".swift", ".kt", ".kts", - ".java", ".gradle", ".groovy", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".go", ".cs", ".pbxproj", ".json5") + ".java", ".gradle", ".groovy", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".go", ".cs", ".pbxproj", ".json5", + ".xcconfig", ".modulemap", ".metal", ".glsl", ".hlsl", ".vert", ".frag", ".comp", ".wgsl", ".S", ".rc", ".idl") HASH = (".sh", ".bash", ".zsh", ".py", ".cmake", ".toml", ".yml", ".yaml", ".rb", ".pl", ".properties", ".podspec", ".ps1", ".mk", ".cfg", ".ini", ".conf") HASH_NAMES = ("CMakeLists.txt", "Makefile", "Podfile", "Gemfile", "Dockerfile") XML = (".xml", ".plist", ".props", ".targets", ".storyboard", ".xib", ".xcscheme", ".xcworkspacedata", ".html") PROSE = (".md", ".markdown", ".rst", ".adoc", ".txt") PROSE_NAMES = re.compile(r"^(LICENSE|NOTICE|THIRD_PARTY_NOTICES|AUTHORS|CHANGELOG)([.-].*)?$|^\.git(ignore|attributes|keep)$") -COMMENT_LINE = re.compile(r"^\s*(#|//|/\*|\*|)", re.S) # Where a file sets a variable to a path: a shell assignment anywhere on a line, CMake's set(), and # get_filename_component() with DIRECTORY, whose value is the dir above the path it is given. SHELL_SET = re.compile(r"(?:^|[\s;&|()])(?:export\s+|local\s+|readonly\s+|declare\s+)?([A-Za-z_]\w*)=" r"(\"[^\"]*\"|'[^']*'|[^\s;&|()]*)") CMAKE_SET = re.compile(r"^\s*(set|get_filename_component)\(\s*([A-Za-z_]\w*)\s+\"?([^\s\")]+)", re.I) -# A variable: ${{ }}, then the named forms (`${X}`, `$(X)`, `$X`), then any other. +# A variable: ${{ }}, then the named forms (`${X}`, `$(X)`, `$X`), then any other (Ruby's #{x} too). VARIABLE = re.compile(r"\$\{\{[^}]*\}\}|\$\{([A-Za-z_]\w*)\}|\$\(([A-Za-z_]\w*)\)|\$([A-Za-z_]\w*)" - r"|\$\{[^}]*\}|\$\([^)]*\)|@[A-Za-z_]\w*@|%[A-Za-z_]\w*%") + r"|\$\{[^}]*\}|\$\([^)]*\)|#\{[^}]*\}|@[A-Za-z_]\w*@|%[A-Za-z_]\w*%") +# A shell's `cd`/`pushd` and where to. +CD = re.compile(r"(?:^|[\s;&|(])(?:cd|pushd)\s+(\"[^\"]*\"|'[^']*'|[^\s;&|)]+)") TOKEN = re.compile(r"[^\s'\"`=;,(){}<>\[\]|&:!]*/[^\s'\"`=;,(){}<>\[\]|&:!]*") # A path given as its segments: path.join(root, 'apps', 'demo'), os.path.join(ROOT, "x"). JOIN = re.compile(r"\b(?:join|resolve)\(([^()]*)\)") @@ -908,22 +973,19 @@ def texts(rev): BLOBS = {} # each blob's text, None for a binary, kept across revs -MATCHED = {} # the paths each pattern with a glob or variable matches, by (pattern, tree) +MATCHED = {} # by rev, the paths each pattern with a glob or variable matches def code(text, p): - """The file's text without its comments, by the kind of file p is; None for prose.""" + """The file's text without its comments, by the kind of file p is (whole, for a kind whose + comments are not known: a path read for one is the safe mistake); None for prose.""" name = posixpath.basename(p) - ext = posixpath.splitext(name)[1].lower() - if PROSE_NAMES.match(name) or (ext in PROSE and name not in HASH_NAMES): + ext = posixpath.splitext(name)[1] + if PROSE_NAMES.match(name) or (ext.lower() in PROSE and name not in HASH_NAMES): return None - if ext in C_LIKE: - return re.sub(r"(?", " ", text, flags=re.S) - if ext in HASH or name in HASH_NAMES: - return re.sub(r"(?m)(^|\s)#.*$", r"\1", text) - return "\n".join(line for line in text.split("\n") if not COMMENT_LINE.match(line)) + syntax = (C_COMMENT if ext in C_LIKE or ext.lower() in C_LIKE else XML_COMMENT if ext.lower() in XML + else HASH_COMMENT if ext.lower() in HASH or name in HASH_NAMES else None) + return text if syntax is None else syntax.sub(lambda m: " " if m.group(1) else m.group(0), text) def expand(text, values): @@ -940,7 +1002,7 @@ def expand(text, values): return [text[:m.start()] + option + rest for option in options for rest in rests] -def resolve_token(token, here, entries): +def resolve_token(token, here, entries, matched): """The tracked files and dirs a path in a file can name: from the repo or the file's dir, with WILD and globs standing for one segment. A path that goes up (`..`), or starts at a dir the file does not name (an unknown variable, or `"/../x"` after env!("CARGO_MANIFEST_DIR") or the like), @@ -972,25 +1034,27 @@ def resolve_token(token, here, entries): found.add(path) continue parts = path.split("/") - if (path, id(entries)) not in MATCHED: + if path not in matched: pattern = re.compile("^" + "/".join("[^/]*".join(map(re.escape, re.split(WILDS + "+", s))) for s in parts) + "$") - MATCHED[path, id(entries)] = {p for p in entries if pattern.match(p)} - matched = MATCHED[path, id(entries)] + matched[path] = {p for p in entries if pattern.match(p)} literal = "/".join(parts[:next(i for i, s in enumerate(parts) if re.search(WILDS, s))]) - found |= matched or ({literal} if literal in entries else set()) + found |= matched[path] or ({literal} if literal in entries else set()) return found -def names(text, here, entries): - """The tracked files and dirs the text's paths name (see resolve_token).""" - return set().union(*(resolve_token(token, here, entries) for token in path_tokens(text))) +def names(text, here, entries, matched=None): + """The tracked files and dirs the text's paths name (see resolve_token), with matched a cache + for the tree entries come from.""" + matched = {} if matched is None else matched + return set().union(*(resolve_token(token, here, entries, matched) for token in path_tokens(text))) @functools.lru_cache(maxsize=None) def path_tokens(text): """The paths the text names, but the values it sets variables to, with the variables it sets - expanded. The text is code: its comments already gone.""" - values, found = {}, set() + expanded, and each relative path also from the dir the text has `cd` to. The text is code: its + comments already gone.""" + values, found, cwd = {}, set(), None def define(name, value): # A value that is not a plain path (a command's output, say) is unknown. @@ -1005,19 +1069,28 @@ def define(name, value): continue for m in SHELL_SET.finditer(line): define(m.group(1), m.group(2)) + dirs = [cwd] + cd = CD.search(line) + if cd and cd.group(1).strip("'\"") != "-": + to = expand(cd.group(1).strip("'\""), values)[0] + to = to if re.match(r"^[\w./@+" + WILD + "-]*$", to) else WILD + cwd = to if cwd is None or to.startswith(("/", WILD)) else posixpath.join(cwd, to) + dirs.append(cwd) for expanded in expand(SHELL_SET.sub(" ", line), values): tokens = TOKEN.findall(expanded) for m in JOIN.finditer(expanded): args = [a.strip() for a in m.group(1).split(",")] tokens.append("/".join(a[1:-1] if len(a) > 1 and a[0] == a[-1] and a[0] in "'\"" else WILD for a in args)) found.update(tokens) + found.update(posixpath.join(d, t) for d in dirs if d for t in tokens if not t.startswith(("/", WILD))) return tuple(sorted(found)) @functools.lru_cache(maxsize=None) def named_paths(rev, p): text = code(texts(rev)[p], p) - return frozenset() if text is None else frozenset(names(text, posixpath.dirname(p), ni.tree_entries(rev))) + return frozenset() if text is None else frozenset( + names(text, posixpath.dirname(p), ni.tree_entries(rev), MATCHED.setdefault(rev, {}))) @functools.lru_cache(maxsize=None) diff --git a/tools/tests/test_native_inputs.py b/tools/tests/test_native_inputs.py index 106d4f908..2400dd707 100644 --- a/tools/tests/test_native_inputs.py +++ b/tools/tests/test_native_inputs.py @@ -18,6 +18,7 @@ import sys import tempfile import unittest +from unittest import mock sys.dont_write_bytecode = True # no __pycache__ beside the scripts HERE = os.path.dirname(os.path.abspath(__file__)) @@ -127,6 +128,7 @@ def test_a_make_target_from_the_matrix_counts_once_per_leg(self): self.assertEqual(values, {"platform": ["ios", "tvos"]}) self.assertEqual(check.commands(step("run: make ${{ matrix.platform }}-svg"), "t", values)[3], (["ios-svg", "tvos-svg"], [])) self.assertRaises(ni.Failure, check.commands, step("run: make ${{ matrix.target }}"), "t", values) + self.assertRaises(ni.Failure, check.matrix_values, [" strategy:", " matrix:", " platform: [ios,", " tvos]"]) def test_what_the_environment_can_change_in_the_makefile(self): self.assertEqual(check.make_environment("x:\n\t$(if $(CI),a.sh,b.sh)\n", []), ["CI"]) @@ -134,9 +136,11 @@ def test_what_the_environment_can_change_in_the_makefile(self): self.assertEqual(check.make_environment("x:\n\t./$(S)\n", ["S=a.sh"]), []) self.assertEqual(check.make_environment( "T ?= nightly\nf = echo $(1)\nx:\n\tcargo +$(T) $(call f,a) $(foreach v,a b,$(v)) $$(HOME)\n", []), []) - for makefile in ("t:\n\tS=x.sh cargo test\nx:\n\t./$(S)\n", "x:\n\t./$(S:.sh=-2.sh)\n", "x:\n\t./$S\n"): + for makefile in ("t:\n\tS=x.sh cargo test\nx:\n\t./$(S)\n", "x:\n\t./$(S:.sh=-2.sh)\n", "x:\n\t./$S\n", + "S ?= a\nx:\n\tinclude $(S).mk\n"): with self.subTest(makefile=makefile): self.assertEqual(check.make_environment(makefile, []), ["S"]) + self.assertEqual(check.make_environment("x: S := a.sh\ndefine B\necho\nendef\nx:\n\t./$(S) $(B)\n", []), []) class Yaml(unittest.TestCase): @@ -232,6 +236,20 @@ def test_comments_by_the_kind_of_file(self): self.assertEqual(named(check.code("# tools/assets\necho x # tools/assets\nls ${#a}", "a.sh")), set()) self.assertIsNone(check.code("see tools/assets", "packages/x/platforms/README.md")) + def test_a_comment_marker_in_a_string_is_text(self): + for text in ('g("x/*/y");\nread("tools/assets/icons/a.png");\n/* z */', 'f("a//b", read("tools/assets/icons/a.png"));'): + with self.subTest(text=text): + self.assertEqual(named(check.code(text, "a.rs")), {"tools/assets/icons/a.png"}) + self.assertEqual(named(check.code('s.source = "#{root}/tools/assets/icons/a.png"', "a.podspec")), {"tools/assets/icons/a.png"}) + self.assertEqual(check.code("#include tools/assets", "a.unknown"), "#include tools/assets") + + def test_after_a_cd(self): + self.assertEqual(named("cd packages/canvas/src-native/android\ncp ../../platforms/ios/src/cpp/Caches.cpp x"), + {"packages/canvas/src-native/android", "packages/canvas/platforms/ios/src/cpp/Caches.cpp"}) + + def test_the_words_made_of_a_matrix_value(self): + self.assertEqual(check.apart("cp a/b x/${{ matrix.n }}/y z"), ("cp a/b z", "x/${{ matrix.n }}/y")) + def test_a_matrix_value_is_one_segment_or_each_listed_value(self): self.assertEqual(named("cp packages/${{ matrix.name }}/platforms x"), {"packages/canvas/platforms"}) self.assertEqual(check.each_leg("cp packages/${{ matrix.m.name }}/x/${{ matrix.arch }}", {"m.name": ["a"], "arch": ["x64", "arm64"]}), @@ -390,9 +408,17 @@ def test_the_wiring(self): guarded = " - name: Build Rust libraries\n if: steps.native.outputs.hit != 'true'\n run: make android" for name, new in (("unguarded", " - name: Build Rust libraries\n run: make android"), ("|| guard", guarded.replace("!= 'true'", "!= 'true' || always()")), + ("status function", guarded.replace("!= 'true'", "!= 'true' && !success()")), ("run context", guarded.replace("run: make android", "run: echo ${{ github.sha }} && make android"))): with self.subTest(name=name): self.assertRaises(ni.Failure, check.check_wiring, self.edit(ni.BUILD_NATIVE, guarded, new)) + upload = " - uses: actions/upload-artifact@v4\n with:\n name: canvas-android\n" + for name, new in (("renamed upload", upload.replace("name: canvas-android", "name: android")), ("no upload", "")): + with self.subTest(name=name): + self.assertRaises(ni.Failure, check.check_wiring, self.edit( + ni.BUILD_NATIVE, upload + " path: packages/canvas/platforms/android/canvas-release.aar\n" + " if-no-files-found: error\n", new and new + " path: packages/canvas/platforms/android/" + "canvas-release.aar\n if-no-files-found: error\n")) self.assertRaises(ni.Failure, check.check_wiring, self.edit(ni.BUILD_NATIVE, " variant: ${{ toJSON(matrix) }}\n", "")) # GitHub evaluates expressions in an action's input descriptions and fails to load it. @@ -423,6 +449,18 @@ def test_check_fails_a_build_file_naming_a_crate_outside_the_closure(self): rev = self.commit("packages/audio-context/src-native/android/extra.gradle", 'cargo { module = "../../../../crates/canvas-core" }\n') self.assertTrue(any("crates/canvas-core" in p for p in self.problems("audio-context-android", rev))) + def test_a_shared_job_counts_only_matrix_made_paths_against_its_legs(self): + build = " run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi ${{ matrix.module.crate }}" + for line, flagged in (("cp -R packages/canvas-media/platforms/windows/x64/ x", True), + ("cp -R packages/${{ matrix.module.name }}/platforms/windows/x64/ x", False)): + with self.subTest(line=line): + rev = self.edit(ni.BUILD_NATIVE, build, build.replace("run: ", f"run: {line} && ")) + self.assertEqual(any("canvas-media/platforms/windows" in p for p in self.problems("canvas-svg-windows", rev)), flagged) + + def test_an_output_without_crates_needs_no_cargo(self): + with mock.patch.object(ni, "crate_meta", side_effect=AssertionError("ran cargo")): + ni.key_inputs("audio-context-android", self.base) + if __name__ == "__main__": sys.exit(unittest.main(verbosity=1)) From df47e5156d9b3438ee5926f4145973555db5f0e9 Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:30:45 +0800 Subject: [PATCH 04/12] ci: split the native cache check into its three parts check-native-inputs.py held a job reader, a key scanner and the wiring rules in one 1,170-line file. They now live in tools/tests/native_check (jobs.py, paths.py, wiring.py), with explicit imports between them, and check-native-inputs.py keeps the spec, the check that runs both passes and main. The code moved unchanged: the tests and every earlier review's reproductions give the same results. --- tools/tests/check-native-inputs.py | 1049 +------------------------- tools/tests/native_check/__init__.py | 9 + tools/tests/native_check/jobs.py | 577 ++++++++++++++ tools/tests/native_check/paths.py | 283 +++++++ tools/tests/native_check/wiring.py | 206 +++++ tools/tests/test_native_inputs.py | 93 ++- 6 files changed, 1124 insertions(+), 1093 deletions(-) create mode 100644 tools/tests/native_check/__init__.py create mode 100644 tools/tests/native_check/jobs.py create mode 100644 tools/tests/native_check/paths.py create mode 100644 tools/tests/native_check/wiring.py diff --git a/tools/tests/check-native-inputs.py b/tools/tests/check-native-inputs.py index f58a6c2cf..04a231f04 100644 --- a/tools/tests/check-native-inputs.py +++ b/tools/tests/check-native-inputs.py @@ -61,605 +61,20 @@ Needs git, Python 3.8+, cargo and make. """ import argparse -import collections import functools -import importlib.util import os -import posixpath import re -import subprocess import sys -import tempfile -sys.dont_write_bytecode = True # no __pycache__ beside the key module -_spec = importlib.util.spec_from_file_location( - "native_inputs", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "scripts", "native-inputs.py")) -ni = importlib.util.module_from_spec(_spec) -_spec.loader.exec_module(ni) +sys.dont_write_bytecode = True # no __pycache__ beside the parts or the key module +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the parts, however this is loaded -# skia-cache names every platform's build scripts, only to hash them. -SKIA_CACHE = ".github/actions/skia-cache" -GUARD = "steps.native.outputs.hit != 'true'" -# Scripts that build a third-party library from its own sources with its own make. -OWN_MAKE = {f"packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/{name}" - for name in ("build_opus_deps.sh", "build_opus_deps_ios.sh")} -SCRIPT_EXT = r"(?:sh|bash|py|js|mjs|cjs|ts|rb|pl|ps1)" -SHELLS = {"sh", "bash", "zsh", "dash", "source", "."} -# The option that makes each interpreter run code given inline rather than a file. -INLINE_CODE = {**{s: {"-c"} for s in SHELLS}, "python": {"-c"}, "python3": {"-c"}, "py": {"-c"}, - "node": {"-e", "--eval", "-p", "--print"}, "ruby": {"-e"}, "perl": {"-e", "-E"}, - "pwsh": {"-Command", "-c", "-EncodedCommand"}, "powershell": {"-Command", "-c", "-EncodedCommand"}} -INTERPRETERS = set(INLINE_CODE) -# Interpreter options whose value is the next argument (so the script is the one after it). -VALUE_OPTIONS = {"-o", "+o", "-O", "+O", "-W", "-X", "-r", "--require", "--import", "--loader", - "-ExecutionPolicy", "-ep"} -# Commands that run the command after them, with their options that take a value. -WRAPPERS = {"sudo": {"-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U"}, "env": {"-u", "-C", "-S"}, - "nice": {"-n"}, "timeout": {"-s", "-k"}, "time": {"-f", "-o"}, "exec": {"-a"}, - "xargs": {"-n", "-I", "-P", "-L", "-s", "-d", "-E", "-a"}, "nohup": set(), "command": set(), - "arch": set()} -KEYWORDS = {"if", "then", "elif", "else", "while", "until", "do", "!", "{", "}"} -# Commands whose arguments name a program without running it: lookups, output, package installs. -NAMES_ONLY = {"which", "type", "hash", "echo", "printf", "apt", "apt-get", "brew", "choco", "dnf", "yum", - "pacman", "port", "apk", "winget", "zypper"} -PACKAGE_RUNNERS = {"npm", "npx", "yarn", "pnpm", "nx", "bun", "just"} -CARGO_BUILDS = {"build", "b", "test", "t", "check", "c", "run", "r", "bench", "clippy", "doc", "d", "rustc"} -WORKSPACE_PREFIX = re.compile(r"\$\{\{\s*github\.workspace\s*\}\}/|\$\{?(?:GITHUB_WORKSPACE|ROOT|REPO_ROOT|PWD)\}?/") -# A context in an expression, with the field it reads (`.x` or `['x']`), if any. -CONTEXT = re.compile(r"(?][-+0-9]*" + ni.COMMENT + r"\s*$", value): - body = [] - for rest in step[i + 1:]: - if rest.strip() and ni.indent(rest) <= ni.key_indent(line): - break - body.append(rest) - return "\n".join(body) - following = next((l for l in step[i + 1:] if l.strip()), "") - if following and ni.indent(following) > ni.key_indent(line): - raise ni.Failure(f"`{name}:` continues on the next lines; write it as `{name}: |` so it can be read") - value = re.sub(r"\s+#.*$", "", value).strip() - if len(value) > 1 and value[0] == value[-1] and value[0] in "'\"": - value = value[1:-1] - return value - return "" - - -def is_dynamic(token): - return re.search(r"[$*?{}\[\]]", token) is not None - - -def looks_like_file(token): - return "/" in token or re.search(r"\." + SCRIPT_EXT + "$", token) is not None - - -# What a script calls its own dir: `$(dirname "$0")`, `$(dirname "${BASH_SOURCE[0]}")`, -# `${BASH_SOURCE[0]%/*}`, `$SCRIPT_DIR`. -SCRIPT_DIR_REF = re.compile(r"\$\(\s*dirname\s+\"?\$(?:0|\{BASH_SOURCE\[0\]\}|BASH_SOURCE)\"?\s*\)" - r"|\$\{BASH_SOURCE\[0\]%/\*\}|\$\{?SCRIPT_DIR\}?") - - -def mentions(text, bases, tree, script_dir=None): - """The tracked files (not dirs) the text names, relative to the repo or to one of bases, and - with script_dir, to what the script calls its own dir. Workflow files are left out: each job's - own block is its input, and a script's message naming the ni.workflow (canvas-build.sh does) would - otherwise rebuild a job for an edit to any other job.""" - found = set() - text = WORKSPACE_PREFIX.sub("", text.replace("\\", "/")) - if script_dir is not None: - text = SCRIPT_DIR_REF.sub("@SCRIPT_DIR@", text) - for token in re.findall(r"[^\s'\"`=;&|()<>,]+", text): - token = token.rstrip(".:") - own = token.startswith("@SCRIPT_DIR@/") - if own: - token = token[len("@SCRIPT_DIR@/"):] - if is_dynamic(token): - continue - for base in ([script_dir] if own else ["", *bases]): - try: - path = ni.norm(posixpath.join(base, token)) - except ni.Failure: - continue - if path in tree and not path.startswith(".github/workflows/"): - found.add(path) - return found - - -def shell_commands(script, where): - """The commands in shell text, each a list of its words with quotes removed. Commands end at - ; & | ( ) ` $( and newlines outside quotes; text inside quotes stays in its word, so a word that - ran something computed keeps its `$`. A backslash escapes a quote, `$`, a space or another - backslash, and otherwise reads as `/` (the Windows jobs' paths). Heredoc bodies and redirection - targets are dropped. An unclosed quote is an error rather than a script swallowed whole.""" - commands, words, word, quote, i = [], [], None, None, 0 - heredocs, drop_next = [], False - - def end_word(): - nonlocal word, drop_next - if word is not None: - if drop_next: - drop_next = False - else: - words.append(word) - word = None - - def end_command(): - nonlocal words, drop_next - end_word() - if words: - commands.append(words) - words, drop_next = [], False - - while i < len(script): - c = script[i] - nxt = script[i + 1] if i + 1 < len(script) else "" - if quote: - if c == quote: - quote = None - elif c == "\\" and quote == '"' and nxt in '"$`\\': - word += nxt - i += 1 - else: - word += "/" if c == "\\" else c - elif c == "\\" and nxt and nxt in "'\"$ \\": - word = (word or "") + nxt - i += 1 - elif c in "'\"": - quote, word = c, word or "" - elif c == "#" and word is None: - while i < len(script) and script[i] != "\n": - i += 1 - continue - elif script.startswith("<<", i) and not script.startswith("<<<", i): - end_word() - m = re.match(r"<<-?\s*['\"]?([A-Za-z0-9_]+)['\"]?", script[i:]) - if not m: - raise ni.Failure(f"{where}: cannot read the heredoc at `{script[i:i + 20].strip()}`") - heredocs.append(m.group(1)) - i += m.end() - continue - elif c in "<>": - if word is not None and word.isdigit(): - word = None - end_word() - drop_next = True - while i + 1 < len(script) and script[i + 1] in "<>&": - i += 1 - elif script.startswith(("&&", "||", "$("), i): - end_command() - i += 2 - continue - elif c == "\n": - end_command() - while heredocs: - delimiter = heredocs.pop(0) - i += 1 - while i < len(script): - j = script.find("\n", i) - line = script[i:] if j < 0 else script[i:j] - i = len(script) if j < 0 else j - if line.strip() == delimiter: - break - i += 1 - else: - raise ni.Failure(f"{where}: the heredoc ending `{delimiter}` is not closed") - i -= 1 if i < len(script) else 0 - elif c in ";&|()`": - end_command() - elif c.isspace(): - end_word() - else: - word = (word or "") + ("/" if c == "\\" else c) - i += 1 - if quote: - raise ni.Failure(f"{where}: a {quote} quote is never closed, so what runs after it cannot be read") - if heredocs: - raise ni.Failure(f"{where}: the heredoc ending `{heredocs[0]}` is not closed") - end_command() - return commands - - -def is_absolute(token): - return token.startswith(("/", "~")) or re.match(r"^[A-Za-z]:/", token) is not None - - -def matrix_values(strategy): - """{key: [values]} of the values a job's strategy lists for each matrix key: `platform: [ios, - tvos]`, a list of scalars, a list of maps (`module.name`), and include's maps (their own keys).""" - lines = [l for l in strategy if l.strip()] - start = next((i for i, l in enumerate(lines) if re.match(r"^\s+matrix:\s*$", l)), None) - if start is None: - return {} - values, key, column = {}, None, None - for line in lines[start + 1:]: - if ni.indent(line) <= ni.indent(lines[start]): - break - column = column if column is not None else ni.indent(line) - m = re.match(r"^\s*(-\s+)?([\w-]+):\s*(.*?)\s*$", line) or re.match(r"^\s*(-\s+)()(.+?)\s*$", line) - if not m: - continue - dash, name, value = m.groups() - if value.startswith(("[", "{")) and not value.endswith(("]", "}")): - raise ni.Failure(f"write the matrix's `{name}:` on one line, so its values can be read: {line.strip()}") - if ni.indent(line) == column and not dash: - key = name - if value.startswith("["): - values[key] = [v.strip().strip("'\"") for v in value.strip("[]").split(",") if v.strip()] - continue - if key is None: - continue - if dash and not name: - values.setdefault(key, []).append(value.strip("'\"")) - continue - field_key = name if key == "include" else f"{key}.{name}" - if value and not value.startswith(("[", "{")): - values.setdefault(field_key, []) - if value.strip("'\"") not in values[field_key]: - values[field_key].append(value.strip("'\"")) - return values - - -MATRIX = re.compile(r"\$\{\{\s*matrix\.([\w.-]+)\s*\}\}") -MATRIX_WORD = re.compile(r"[^\s'\"]*\x03[\w.-]+\x03[^\s'\"]*") - - -def marked(script): - """The script with each matrix value marked without the spaces `${{ }}` holds, so it stays in - its word.""" - return MATRIX.sub(lambda m: f"\x03{m.group(1)}\x03", script) - - -def unmarked(script): - return re.sub(r"\x03([\w.-]+)\x03", lambda m: "${{ matrix." + m.group(1) + " }}", script) - - -def apart(script): - """(the script without its words that hold a matrix value, and those words, a line each).""" - script = marked(script) - return unmarked(MATRIX_WORD.sub(" ", script)), unmarked("\n".join(MATRIX_WORD.findall(script))) - - -def each_leg(script, values): - """The script with each word that holds a matrix value the strategy lists written once per value, - so `make ${{ matrix.platform }}` reads as one make of every leg's target.""" - script = marked(script) - for key, options in values.items(): - mark = f"\x03{key}\x03" - script = re.sub(r"[^\s'\"]*" + re.escape(mark) + r"[^\s'\"]*", - lambda m: " ".join(m.group(0).replace(mark, v) for v in options), script) - return unmarked(script) - - -def commands(step, where, values=None): - """What a step's run: text runs: (wd, files, guesses, make targets and variables). files must - exist; guesses are (what, path) for a script argument without `/` or extension, which has to.""" - wd = field(step, "working-directory") - files, guesses, makes = set(), [], [] - script = WORKSPACE_PREFIX.sub("", each_leg(re.sub(r"\\\n", " ", field(step, "run")), values or {})) - for line in script.split("\n"): - if re.search(r"(^|[\s;&|(!{])(?:\S*/)?g?make\s[^\n]*(\$\(|`|\$\{\{)", line): - raise ni.Failure(f"{where}: cannot follow make with a computed argument: `{line.strip()}`") - walk(script, wd, where, files, guesses, makes, False) - if len(makes) > 1: - raise ni.Failure(f"{where}: runs make more than once; give each its own step") - return wd, files, guesses, (makes[0] if makes else None) - - -def unwrap(tokens): - """The command a shell command runs, past keywords, assignments and wrappers with their - options; [] for `command -v`, which only looks one up.""" - while tokens: - word = tokens[0] - if word in WRAPPERS: - tokens = tokens[1:] - if word == "command" and tokens and tokens[0] in ("-v", "-V"): - return [] - while tokens and tokens[0].startswith("-"): - option, tokens = tokens[0], tokens[1:] - if option in WRAPPERS[word] and tokens: - tokens = tokens[1:] - if word == "timeout" and tokens and re.match(r"^\d+(\.\d+)?[smhd]?$", tokens[0]): - tokens = tokens[1:] - elif word in KEYWORDS or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", word): - tokens = tokens[1:] - else: - break - return tokens - - -def walk(script, wd, where, files, guesses, makes, after_cd): - for tokens in shell_commands(script, where): - command = " ".join(tokens) - tokens = unwrap(tokens) - if not tokens: - continue - name, args = tokens[0], tokens[1:] - base = posixpath.basename(name) - first = next((a for a in args if not a.startswith(("-", "+"))), "") - # A make that a wrapper this does not know starts (`chrt 10 make`) would read as an argument. - if base not in ("make", "gmake") and base not in NAMES_ONLY and any( - posixpath.basename(a) in ("make", "gmake") for a in args): - raise ni.Failure(f"{where}: cannot follow the make in `{command}`; run `make ` itself") - if base in PACKAGE_RUNNERS: - raise ni.Failure(f"{where}: `{command}` runs what a package manifest says; run the script itself") - if base == "cargo" and first in CARGO_BUILDS and not (wd or after_cd) and ( - {"--workspace", "--all"} & set(args) or not any( - a in ("-p", "--package", "--manifest-path") or a.startswith(("--package=", "--manifest-path=")) - or (a.startswith("-p") and not a.startswith("--")) for a in args)): - raise ni.Failure(f"{where}: `{command}` builds crates it does not name; name each with -p") - if name in ("cd", "pushd"): - after_cd = True - elif base in ("make", "gmake"): - makes.append(make_command(args, wd or after_cd, command, where)) - elif base in INTERPRETERS: - if base in ("python", "python3", "py") and "-m" in args: - raise ni.Failure(f"{where}: cannot tell which file `{command.strip()}` runs; run the file itself") - if base in SHELLS and "-c" in args: - code = args[args.index("-c") + 1] if args.index("-c") + 1 < len(args) else "" - after_cd = walk(code, wd, where, files, guesses, makes, after_cd) - continue - if any(a in INLINE_CODE[base] for a in args): - continue - script_arg, skip_value = None, False - for arg in args: - if skip_value: - skip_value = False - elif arg in VALUE_OPTIONS: - skip_value = True - elif not arg.startswith(("-", "+")): - script_arg = arg - break - if script_arg is None or is_dynamic(script_arg) or is_absolute(script_arg): - continue - if after_cd: - raise ni.Failure(f"{where}: runs `{command.strip()}` after `cd`; give the step a working-directory instead") - path = ni.norm(posixpath.join(wd, script_arg)) - if looks_like_file(script_arg): - files.add(path) - else: - guesses.append((f"{where}: `{command.strip()}`", path)) - elif "/" in name and not is_absolute(name) and not is_dynamic(name): - if after_cd: - raise ni.Failure(f"{where}: runs `{name}` after `cd`; give the step a working-directory instead") - files.add(ni.norm(posixpath.join(wd, name))) - return after_cd - - -def make_command(args, moved, command, where): - """([targets], [VAR=value]) of `make [-jN] [VAR=value] ` from the repo root.""" - if moved or any(re.match(r"^(-C|-f|--directory|--file|--makefile)", a) for a in args): - raise ni.Failure(f"{where}: only `make ` from the repo root is followed: `{command.strip()}`") - targets, variables, i = [], [], 0 - while i < len(args): - arg = args[i] - if arg in ("-j", "-l") and i + 1 < len(args) and re.match(r"^\d+$", args[i + 1]): - i += 1 - elif "=" in arg and not arg.startswith("-"): - variables.append(arg) - elif not arg.startswith("-"): - targets.append(arg) - i += 1 - if not targets: - raise ni.Failure(f"{where}: name the targets of `{command.strip()}`, so what it runs can be followed") - return targets, variables - - -def make_environment(makefile, variables): - """The variables a Makefile's commands can take from the environment: those it reads but never - sets (a function's own, `$(call f,x)`'s $(1) and $(foreach x,...)'s x, are set, as are a - target's own, `t: X := y`, and `define X`), and its `?=` defaults where they make a path.""" - makefile = makefile.replace("$$", "") - # Not a recipe's (tab-indented) shell assignment, which sets nothing for make. - assignment = r"(?:export[ \t]+|override[ \t]+)?([A-Za-z_][\w.-]*)[ \t]*(?::{1,3}=|\+=|\?=|=)" - set_here = set(re.findall(r"^(?!\t)[ ]*" + assignment, makefile, re.M)) - set_here |= set(re.findall(r"^(?!\t)[^:=#\n]+:(?!=)[ \t]*" + assignment, makefile, re.M)) - set_here |= set(re.findall(r"^define\s+([A-Za-z_][\w.-]*)", makefile, re.M)) - set_here |= {v.split("=", 1)[0] for v in variables} | set(re.findall(r"\$\(foreach\s+([\w.-]+)\s*,", makefile)) - defaults = set(re.findall(r"^\s*([A-Za-z_][\w.-]*)\s*\?=", makefile, re.M)) - found = [] - # $(X), ${X}, $(X:a=b) and $X. - for m in re.finditer(r"\$[({]([A-Za-z_][\w.-]*)(?=[:)}])|\$([A-Za-z_])", makefile): - name = m.group(1) or m.group(2) - if name not in set_here and name not in ("MAKE", "MAKEFLAGS", "MAKECMDGOALS", "SHELL"): - found.append(name) - for name in defaults: - # Next to a path's characters: `dir/$(X)`, `$(X)/lib.a`, `$(X).mk`, `$(X)-out`. - if re.search(rf"[\w./-]\$[({{]{re.escape(name)}[)}}]|\$[({{]{re.escape(name)}[)}}][\w./-]", makefile): - found.append(name) - return sorted(set(found)) - - -def make_commands(rev, targets, variables): - """What `make -n` runs, with the commit's Makefile and no inherited variables. A Makefile that - can run other commands than it prints (conditionals, includes, $(shell)), that names the dir - make runs in, or whose commands the environment can change, is refused.""" - makefile = ni.show(rev, "Makefile") - if re.search(r"^\s*(ifeq|ifneq|ifdef|ifndef|-?include|sinclude)\b|^[^#\n]*!=" - r"|\$[({](shell|origin|wildcard|realpath|abspath|CURDIR)\b", makefile, re.M): - raise ni.Failure("the Makefile has conditionals, includes, $(shell) or paths of the dir make runs " - "in: `make -n` cannot show what a job runs") - for name in make_environment(makefile, variables): - raise ni.Failure(f"the Makefile reads {name} from the environment, which `make -n` does not see: set " - f"it in the Makefile (with =, or ?= where it names no path) or pass it as {name}=...") - with tempfile.TemporaryDirectory() as tmp: - try: - result = subprocess.run(["make", "-n", "-f", "-", *variables, *targets], input=makefile.encode(), - cwd=tmp, capture_output=True, env={"PATH": os.environ.get("PATH", "")}) - except FileNotFoundError: - raise ni.Failure("the job runs make, and make is not installed") - output = result.stdout.decode("utf-8").replace("\r", "") - if os.path.basename(tmp) in output: - raise ni.Failure(f"make -n {' '.join(targets)} prints the dir it ran in, so what it runs cannot be followed") - if result.returncode != 0: - raise ni.Failure(f"make -n {' '.join(targets)}: {result.stderr.decode(errors='replace').strip()}") - return output - - -def named_crates(rev, corpus): - """The members the text names by package name, as a word of its own (`-p canvas-ios`, not - packages/canvas/src-native/canvas-android), or by dir, after any prefix (`$ROOT/crates/x`).""" - _, names, _, _ = ni.crate_meta(rev) - return {member for name, member in names.items() - if re.search(rf"(?)", re.S) -# Where a file sets a variable to a path: a shell assignment anywhere on a line, CMake's set(), and -# get_filename_component() with DIRECTORY, whose value is the dir above the path it is given. -SHELL_SET = re.compile(r"(?:^|[\s;&|()])(?:export\s+|local\s+|readonly\s+|declare\s+)?([A-Za-z_]\w*)=" - r"(\"[^\"]*\"|'[^']*'|[^\s;&|()]*)") -CMAKE_SET = re.compile(r"^\s*(set|get_filename_component)\(\s*([A-Za-z_]\w*)\s+\"?([^\s\")]+)", re.I) -# A variable: ${{ }}, then the named forms (`${X}`, `$(X)`, `$X`), then any other (Ruby's #{x} too). -VARIABLE = re.compile(r"\$\{\{[^}]*\}\}|\$\{([A-Za-z_]\w*)\}|\$\(([A-Za-z_]\w*)\)|\$([A-Za-z_]\w*)" - r"|\$\{[^}]*\}|\$\([^)]*\)|#\{[^}]*\}|@[A-Za-z_]\w*@|%[A-Za-z_]\w*%") -# A shell's `cd`/`pushd` and where to. -CD = re.compile(r"(?:^|[\s;&|(])(?:cd|pushd)\s+(\"[^\"]*\"|'[^']*'|[^\s;&|)]+)") -TOKEN = re.compile(r"[^\s'\"`=;,(){}<>\[\]|&:!]*/[^\s'\"`=;,(){}<>\[\]|&:!]*") -# A path given as its segments: path.join(root, 'apps', 'demo'), os.path.join(ROOT, "x"). -JOIN = re.compile(r"\b(?:join|resolve)\(([^()]*)\)") -WILD = "\x01" -WILDS = r"[*?" + WILD + "]" - - -@functools.lru_cache(maxsize=None) -def blobs(rev): - """{path: (id, size)} of every tracked file at rev.""" - out = {} - for record in ni.git("ls-tree", "-r", "-l", "-z", rev).split("\0"): - if record: - meta, path = record.split("\t", 1) - _, kind, oid, size = meta.split() - if kind == "blob": - out[path] = (oid, int(size)) - return out - - -@functools.lru_cache(maxsize=None) -def texts(rev): - """{path: text} of every tracked text file at rev up to LIMIT.""" - ids = {p: oid for p, (oid, size) in blobs(rev).items() if size <= LIMIT} - missing = sorted({oid for oid in ids.values() if oid not in BLOBS}) - data = ni.git("cat-file", "--batch", data="".join(oid + "\n" for oid in missing).encode(), binary=True) - i = 0 - for oid in missing: - end = data.index(b"\n", i) - size = int(data[i:end].split()[2]) - blob = data[end + 1:end + 1 + size] - i = end + 2 + size - BLOBS[oid] = None if b"\0" in blob[:8000] else blob.decode("utf-8", errors="replace").replace("\r", "") - return {p: BLOBS[oid] for p, oid in ids.items() if BLOBS[oid] is not None} - - -BLOBS = {} # each blob's text, None for a binary, kept across revs -MATCHED = {} # by rev, the paths each pattern with a glob or variable matches - - -def code(text, p): - """The file's text without its comments, by the kind of file p is (whole, for a kind whose - comments are not known: a path read for one is the safe mistake); None for prose.""" - name = posixpath.basename(p) - ext = posixpath.splitext(name)[1] - if PROSE_NAMES.match(name) or (ext.lower() in PROSE and name not in HASH_NAMES): - return None - syntax = (C_COMMENT if ext in C_LIKE or ext.lower() in C_LIKE else XML_COMMENT if ext.lower() in XML - else HASH_COMMENT if ext.lower() in HASH or name in HASH_NAMES else None) - return text if syntax is None else syntax.sub(lambda m: " " if m.group(1) else m.group(0), text) - - -def expand(text, values): - """The text with each variable the file sets replaced by each of its values in turn, and any - other variable (a matrix value too) by WILD.""" - m = VARIABLE.search(text) - if m is None: - return [text] - rests = expand(text[m.end():], values) - name = m.group(1) or m.group(2) or m.group(3) - options = (values.get(name) if name else None) or [WILD] - if len(options) * len(rests) > 64: - options = [WILD] - return [text[:m.start()] + option + rest for option in options for rest in rests] - - -def resolve_token(token, here, entries, matched): - """The tracked files and dirs a path in a file can name: from the repo or the file's dir, with - WILD and globs standing for one segment. A path that goes up (`..`), or starts at a dir the file - does not name (an unknown variable, or `"/../x"` after env!("CARGO_MANIFEST_DIR") or the like), - may start from any dir above the file, and after an unknown dir, the `..` may lead anywhere. A - computed name that matches nothing names its dir.""" - if token.startswith("/.."): - token = WILD + token - unknown = token.startswith(WILD + "/") - token = re.sub(r"^(" + WILD + r"/)+", "", token).rstrip(".") - if token.startswith("/") or "//" in token: - return set() - segments = [s for s in token.split("/") if s] - if not any(re.search(r"[A-Za-z]", s) and not re.search(WILDS, s) for s in segments): - return set() - bases = ["", here] - if unknown or segments[0] == "..": - bases += [here.rsplit("/", n)[0] for n in range(1, here.count("/") + 1)] - forms = [segments] - if unknown and segments[0] == "..": - forms.append(segments[next(i for i, s in enumerate(segments) if s != ".."):]) - found = set() - for base, form in ((b, f) for b in bases for f in forms): - try: - path = ni.norm(posixpath.join(base, *form)) - except ni.Failure: - continue - if not re.search(WILDS, path): - if path in entries: - found.add(path) - continue - parts = path.split("/") - if path not in matched: - pattern = re.compile("^" + "/".join("[^/]*".join(map(re.escape, re.split(WILDS + "+", s))) for s in parts) + "$") - matched[path] = {p for p in entries if pattern.match(p)} - literal = "/".join(parts[:next(i for i, s in enumerate(parts) if re.search(WILDS, s))]) - found |= matched[path] or ({literal} if literal in entries else set()) - return found - - -def names(text, here, entries, matched=None): - """The tracked files and dirs the text's paths name (see resolve_token), with matched a cache - for the tree entries come from.""" - matched = {} if matched is None else matched - return set().union(*(resolve_token(token, here, entries, matched) for token in path_tokens(text))) - - -@functools.lru_cache(maxsize=None) -def path_tokens(text): - """The paths the text names, but the values it sets variables to, with the variables it sets - expanded, and each relative path also from the dir the text has `cd` to. The text is code: its - comments already gone.""" - values, found, cwd = {}, set(), None - - def define(name, value): - # A value that is not a plain path (a command's output, say) is unknown. - values.setdefault(name, []) - values[name] += [v if re.match(r"^[\w./@+" + WILD + "-]*$", v) else WILD - for v in expand(value.strip("'\""), values) if v not in values[name]] - - for line in text.split("\n"): - cmake = CMAKE_SET.match(line) - if cmake: - define(cmake.group(2), cmake.group(3) + ("/.." if cmake.group(1).lower() != "set" else "")) - continue - for m in SHELL_SET.finditer(line): - define(m.group(1), m.group(2)) - dirs = [cwd] - cd = CD.search(line) - if cd and cd.group(1).strip("'\"") != "-": - to = expand(cd.group(1).strip("'\""), values)[0] - to = to if re.match(r"^[\w./@+" + WILD + "-]*$", to) else WILD - cwd = to if cwd is None or to.startswith(("/", WILD)) else posixpath.join(cwd, to) - dirs.append(cwd) - for expanded in expand(SHELL_SET.sub(" ", line), values): - tokens = TOKEN.findall(expanded) - for m in JOIN.finditer(expanded): - args = [a.strip() for a in m.group(1).split(",")] - tokens.append("/".join(a[1:-1] if len(a) > 1 and a[0] == a[-1] and a[0] in "'\"" else WILD for a in args)) - found.update(tokens) - found.update(posixpath.join(d, t) for d in dirs if d for t in tokens if not t.startswith(("/", WILD))) - return tuple(sorted(found)) - - -@functools.lru_cache(maxsize=None) -def named_paths(rev, p): - text = code(texts(rev)[p], p) - return frozenset() if text is None else frozenset( - names(text, posixpath.dirname(p), ni.tree_entries(rev), MATCHED.setdefault(rev, {}))) - - -@functools.lru_cache(maxsize=None) -def files_under(rev): - under = collections.defaultdict(list) - for p, (kind, _) in ni.tree_entries(rev).items(): - d = posixpath.dirname(p) if kind != "tree" else None - while d: - under[d].append(p) - d = posixpath.dirname(d) - return under - - -def crate_of(rev, p): - return next((d for d in sorted(ni.crate_meta(rev)[2], key=len, reverse=True) if p.startswith(d + "/")), None) - - -def crossings(artifact, rev, wanted, source, here, targets): - """The targets that source names and the artifact's key leaves out, but source itself and the - dirs it is in, and NOT_READ's. A crate dir counts when it is outside the closure, unless a - Cargo.toml names it (cargo metadata reads those).""" - entries, under, problems = ni.tree_entries(rev), files_under(rev), [] - crate_dirs, crates = ni.crate_meta(rev)[2], ni.closure(rev, ni.ARTIFACTS[artifact].get("crates", [])) - for target in sorted(targets): - if (target == source or target.startswith(".github/workflows/") or here == target - or here.startswith(target + "/") or not_read(source, target)): - continue - if target in crate_dirs: - if target not in crates and posixpath.basename(source) != "Cargo.toml": - problems.append(f"{artifact}: {source} names the crate {target}, which is outside its crates' " - f"closure; if its job does not read it there, add it to NOT_READ with the reason") - continue - left_out = [f for f in (under[target] if entries[target][0] == "tree" else [target]) if not wanted(f)] - if left_out: - first, crate = left_out[0], crate_of(rev, left_out[0]) - whose = (f"{crate} is outside its crates' closure" if crate and crate not in crates else - f"OWNERS gives {first} to {', '.join(ni.owners(first)) or 'no artifact'}") - what = target if left_out == [target] else f"{len(left_out)} of the files under {target}" - problems.append(f"{artifact}: {source} names {what}, which its key leaves out ({whose}); if its " - f"job does not read it there, add it to NOT_READ with the reason") - return problems - - -def scan(artifact, rev, wanted): - """The paths that the text files in the artifact's key name and its key leaves out, and the files - in it too large to read that are not binaries. The job pass reads the workflows, actions and - Makefile for what the job runs of them.""" - tested = set(ni.ARTIFACTS[artifact].get("crates", [])) if artifact in CARGO_TESTS else set() - problems = [f"{artifact}: {p} is in its key but too large to scan for paths; if it is not text, add its " - f"type to BINARY" for p, (_, size) in sorted(blobs(rev).items()) - if size > LIMIT and wanted(p) and not p.lower().endswith(BINARY)] - for p in sorted(texts(rev)): - if p.startswith(".github/") or p == "Makefile" or not wanted(p): - continue - crate = crate_of(rev, p) - if crate and p[len(crate) + 1:].split("/")[0] in ("tests", "benches", "examples") and crate not in tested: - continue - problems += crossings(artifact, rev, wanted, p, posixpath.dirname(p), named_paths(rev, p)) - return problems - - def main(argv): parser = argparse.ArgumentParser(prog="check-native-inputs.py", description="hold the native cache keys to what their jobs read") diff --git a/tools/tests/native_check/__init__.py b/tools/tests/native_check/__init__.py new file mode 100644 index 000000000..74818dd64 --- /dev/null +++ b/tools/tests/native_check/__init__.py @@ -0,0 +1,9 @@ +"""The parts of tools/tests/check-native-inputs.py (jobs, paths, wiring) and the key module they hold +the keys of, as `ni`.""" +import importlib.util +import os + +_spec = importlib.util.spec_from_file_location( + "native_inputs", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "scripts", "native-inputs.py")) +ni = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(ni) diff --git a/tools/tests/native_check/jobs.py b/tools/tests/native_check/jobs.py new file mode 100644 index 000000000..aac334893 --- /dev/null +++ b/tools/tests/native_check/jobs.py @@ -0,0 +1,577 @@ +"""Reads what a native job runs: its steps, the actions they use, the scripts and files they run, +and what `make -n` prints, with the refusals for what cannot be read. The first pass of +tools/tests/check-native-inputs.py, whose docstring says what it checks.""" +import collections +import os +import posixpath +import re +import subprocess +import tempfile + +from . import ni + + +# skia-cache names every platform's build scripts, only to hash them. +SKIA_CACHE = ".github/actions/skia-cache" +# Scripts that build a third-party library from its own sources with its own make. +OWN_MAKE = {f"packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/{name}" + for name in ("build_opus_deps.sh", "build_opus_deps_ios.sh")} +SCRIPT_EXT = r"(?:sh|bash|py|js|mjs|cjs|ts|rb|pl|ps1)" +SHELLS = {"sh", "bash", "zsh", "dash", "source", "."} +# The option that makes each interpreter run code given inline rather than a file. +INLINE_CODE = {**{s: {"-c"} for s in SHELLS}, "python": {"-c"}, "python3": {"-c"}, "py": {"-c"}, + "node": {"-e", "--eval", "-p", "--print"}, "ruby": {"-e"}, "perl": {"-e", "-E"}, + "pwsh": {"-Command", "-c", "-EncodedCommand"}, "powershell": {"-Command", "-c", "-EncodedCommand"}} +INTERPRETERS = set(INLINE_CODE) +# Interpreter options whose value is the next argument (so the script is the one after it). +VALUE_OPTIONS = {"-o", "+o", "-O", "+O", "-W", "-X", "-r", "--require", "--import", "--loader", + "-ExecutionPolicy", "-ep"} +# Commands that run the command after them, with their options that take a value. +WRAPPERS = {"sudo": {"-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U"}, "env": {"-u", "-C", "-S"}, + "nice": {"-n"}, "timeout": {"-s", "-k"}, "time": {"-f", "-o"}, "exec": {"-a"}, + "xargs": {"-n", "-I", "-P", "-L", "-s", "-d", "-E", "-a"}, "nohup": set(), "command": set(), + "arch": set()} +KEYWORDS = {"if", "then", "elif", "else", "while", "until", "do", "!", "{", "}"} +# Commands whose arguments name a program without running it: lookups, output, package installs. +NAMES_ONLY = {"which", "type", "hash", "echo", "printf", "apt", "apt-get", "brew", "choco", "dnf", "yum", + "pacman", "port", "apk", "winget", "zypper"} +PACKAGE_RUNNERS = {"npm", "npx", "yarn", "pnpm", "nx", "bun", "just"} +CARGO_BUILDS = {"build", "b", "test", "t", "check", "c", "run", "r", "bench", "clippy", "doc", "d", "rustc"} +WORKSPACE_PREFIX = re.compile(r"\$\{\{\s*github\.workspace\s*\}\}/|\$\{?(?:GITHUB_WORKSPACE|ROOT|REPO_ROOT|PWD)\}?/") + + +def field(step, name): + """A step's `name:` value, inline or as a block scalar; "" when it has none.""" + for i, line in enumerate(step): + m = re.match(rf"^\s*(?:-\s+)?{name}:\s*(.*)$", line) + if not m: + continue + value = m.group(1) + if re.match(r"^[|>][-+0-9]*" + ni.COMMENT + r"\s*$", value): + body = [] + for rest in step[i + 1:]: + if rest.strip() and ni.indent(rest) <= ni.key_indent(line): + break + body.append(rest) + return "\n".join(body) + following = next((l for l in step[i + 1:] if l.strip()), "") + if following and ni.indent(following) > ni.key_indent(line): + raise ni.Failure(f"`{name}:` continues on the next lines; write it as `{name}: |` so it can be read") + value = re.sub(r"\s+#.*$", "", value).strip() + if len(value) > 1 and value[0] == value[-1] and value[0] in "'\"": + value = value[1:-1] + return value + return "" + + +def is_dynamic(token): + return re.search(r"[$*?{}\[\]]", token) is not None + + +def looks_like_file(token): + return "/" in token or re.search(r"\." + SCRIPT_EXT + "$", token) is not None + + +# What a script calls its own dir: `$(dirname "$0")`, `$(dirname "${BASH_SOURCE[0]}")`, +# `${BASH_SOURCE[0]%/*}`, `$SCRIPT_DIR`. +SCRIPT_DIR_REF = re.compile(r"\$\(\s*dirname\s+\"?\$(?:0|\{BASH_SOURCE\[0\]\}|BASH_SOURCE)\"?\s*\)" + r"|\$\{BASH_SOURCE\[0\]%/\*\}|\$\{?SCRIPT_DIR\}?") + + +def mentions(text, bases, tree, script_dir=None): + """The tracked files (not dirs) the text names, relative to the repo or to one of bases, and + with script_dir, to what the script calls its own dir. Workflow files are left out: each job's + own block is its input, and a script's message naming the ni.workflow (canvas-build.sh does) would + otherwise rebuild a job for an edit to any other job.""" + found = set() + text = WORKSPACE_PREFIX.sub("", text.replace("\\", "/")) + if script_dir is not None: + text = SCRIPT_DIR_REF.sub("@SCRIPT_DIR@", text) + for token in re.findall(r"[^\s'\"`=;&|()<>,]+", text): + token = token.rstrip(".:") + own = token.startswith("@SCRIPT_DIR@/") + if own: + token = token[len("@SCRIPT_DIR@/"):] + if is_dynamic(token): + continue + for base in ([script_dir] if own else ["", *bases]): + try: + path = ni.norm(posixpath.join(base, token)) + except ni.Failure: + continue + if path in tree and not path.startswith(".github/workflows/"): + found.add(path) + return found + + +def shell_commands(script, where): + """The commands in shell text, each a list of its words with quotes removed. Commands end at + ; & | ( ) ` $( and newlines outside quotes; text inside quotes stays in its word, so a word that + ran something computed keeps its `$`. A backslash escapes a quote, `$`, a space or another + backslash, and otherwise reads as `/` (the Windows jobs' paths). Heredoc bodies and redirection + targets are dropped. An unclosed quote is an error rather than a script swallowed whole.""" + commands, words, word, quote, i = [], [], None, None, 0 + heredocs, drop_next = [], False + + def end_word(): + nonlocal word, drop_next + if word is not None: + if drop_next: + drop_next = False + else: + words.append(word) + word = None + + def end_command(): + nonlocal words, drop_next + end_word() + if words: + commands.append(words) + words, drop_next = [], False + + while i < len(script): + c = script[i] + nxt = script[i + 1] if i + 1 < len(script) else "" + if quote: + if c == quote: + quote = None + elif c == "\\" and quote == '"' and nxt in '"$`\\': + word += nxt + i += 1 + else: + word += "/" if c == "\\" else c + elif c == "\\" and nxt and nxt in "'\"$ \\": + word = (word or "") + nxt + i += 1 + elif c in "'\"": + quote, word = c, word or "" + elif c == "#" and word is None: + while i < len(script) and script[i] != "\n": + i += 1 + continue + elif script.startswith("<<", i) and not script.startswith("<<<", i): + end_word() + m = re.match(r"<<-?\s*['\"]?([A-Za-z0-9_]+)['\"]?", script[i:]) + if not m: + raise ni.Failure(f"{where}: cannot read the heredoc at `{script[i:i + 20].strip()}`") + heredocs.append(m.group(1)) + i += m.end() + continue + elif c in "<>": + if word is not None and word.isdigit(): + word = None + end_word() + drop_next = True + while i + 1 < len(script) and script[i + 1] in "<>&": + i += 1 + elif script.startswith(("&&", "||", "$("), i): + end_command() + i += 2 + continue + elif c == "\n": + end_command() + while heredocs: + delimiter = heredocs.pop(0) + i += 1 + while i < len(script): + j = script.find("\n", i) + line = script[i:] if j < 0 else script[i:j] + i = len(script) if j < 0 else j + if line.strip() == delimiter: + break + i += 1 + else: + raise ni.Failure(f"{where}: the heredoc ending `{delimiter}` is not closed") + i -= 1 if i < len(script) else 0 + elif c in ";&|()`": + end_command() + elif c.isspace(): + end_word() + else: + word = (word or "") + ("/" if c == "\\" else c) + i += 1 + if quote: + raise ni.Failure(f"{where}: a {quote} quote is never closed, so what runs after it cannot be read") + if heredocs: + raise ni.Failure(f"{where}: the heredoc ending `{heredocs[0]}` is not closed") + end_command() + return commands + + +def is_absolute(token): + return token.startswith(("/", "~")) or re.match(r"^[A-Za-z]:/", token) is not None + + +def matrix_values(strategy): + """{key: [values]} of the values a job's strategy lists for each matrix key: `platform: [ios, + tvos]`, a list of scalars, a list of maps (`module.name`), and include's maps (their own keys).""" + lines = [l for l in strategy if l.strip()] + start = next((i for i, l in enumerate(lines) if re.match(r"^\s+matrix:\s*$", l)), None) + if start is None: + return {} + values, key, column = {}, None, None + for line in lines[start + 1:]: + if ni.indent(line) <= ni.indent(lines[start]): + break + column = column if column is not None else ni.indent(line) + m = re.match(r"^\s*(-\s+)?([\w-]+):\s*(.*?)\s*$", line) or re.match(r"^\s*(-\s+)()(.+?)\s*$", line) + if not m: + continue + dash, name, value = m.groups() + if value.startswith(("[", "{")) and not value.endswith(("]", "}")): + raise ni.Failure(f"write the matrix's `{name}:` on one line, so its values can be read: {line.strip()}") + if ni.indent(line) == column and not dash: + key = name + if value.startswith("["): + values[key] = [v.strip().strip("'\"") for v in value.strip("[]").split(",") if v.strip()] + continue + if key is None: + continue + if dash and not name: + values.setdefault(key, []).append(value.strip("'\"")) + continue + field_key = name if key == "include" else f"{key}.{name}" + if value and not value.startswith(("[", "{")): + values.setdefault(field_key, []) + if value.strip("'\"") not in values[field_key]: + values[field_key].append(value.strip("'\"")) + return values + + +MATRIX = re.compile(r"\$\{\{\s*matrix\.([\w.-]+)\s*\}\}") +MATRIX_WORD = re.compile(r"[^\s'\"]*\x03[\w.-]+\x03[^\s'\"]*") + + +def marked(script): + """The script with each matrix value marked without the spaces `${{ }}` holds, so it stays in + its word.""" + return MATRIX.sub(lambda m: f"\x03{m.group(1)}\x03", script) + + +def unmarked(script): + return re.sub(r"\x03([\w.-]+)\x03", lambda m: "${{ matrix." + m.group(1) + " }}", script) + + +def apart(script): + """(the script without its words that hold a matrix value, and those words, a line each).""" + script = marked(script) + return unmarked(MATRIX_WORD.sub(" ", script)), unmarked("\n".join(MATRIX_WORD.findall(script))) + + +def each_leg(script, values): + """The script with each word that holds a matrix value the strategy lists written once per value, + so `make ${{ matrix.platform }}` reads as one make of every leg's target.""" + script = marked(script) + for key, options in values.items(): + mark = f"\x03{key}\x03" + script = re.sub(r"[^\s'\"]*" + re.escape(mark) + r"[^\s'\"]*", + lambda m: " ".join(m.group(0).replace(mark, v) for v in options), script) + return unmarked(script) + + +def commands(step, where, values=None): + """What a step's run: text runs: (wd, files, guesses, make targets and variables). files must + exist; guesses are (what, path) for a script argument without `/` or extension, which has to.""" + wd = field(step, "working-directory") + files, guesses, makes = set(), [], [] + script = WORKSPACE_PREFIX.sub("", each_leg(re.sub(r"\\\n", " ", field(step, "run")), values or {})) + for line in script.split("\n"): + if re.search(r"(^|[\s;&|(!{])(?:\S*/)?g?make\s[^\n]*(\$\(|`|\$\{\{)", line): + raise ni.Failure(f"{where}: cannot follow make with a computed argument: `{line.strip()}`") + walk(script, wd, where, files, guesses, makes, False) + if len(makes) > 1: + raise ni.Failure(f"{where}: runs make more than once; give each its own step") + return wd, files, guesses, (makes[0] if makes else None) + + +def unwrap(tokens): + """The command a shell command runs, past keywords, assignments and wrappers with their + options; [] for `command -v`, which only looks one up.""" + while tokens: + word = tokens[0] + if word in WRAPPERS: + tokens = tokens[1:] + if word == "command" and tokens and tokens[0] in ("-v", "-V"): + return [] + while tokens and tokens[0].startswith("-"): + option, tokens = tokens[0], tokens[1:] + if option in WRAPPERS[word] and tokens: + tokens = tokens[1:] + if word == "timeout" and tokens and re.match(r"^\d+(\.\d+)?[smhd]?$", tokens[0]): + tokens = tokens[1:] + elif word in KEYWORDS or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", word): + tokens = tokens[1:] + else: + break + return tokens + + +def walk(script, wd, where, files, guesses, makes, after_cd): + for tokens in shell_commands(script, where): + command = " ".join(tokens) + tokens = unwrap(tokens) + if not tokens: + continue + name, args = tokens[0], tokens[1:] + base = posixpath.basename(name) + first = next((a for a in args if not a.startswith(("-", "+"))), "") + # A make that a wrapper this does not know starts (`chrt 10 make`) would read as an argument. + if base not in ("make", "gmake") and base not in NAMES_ONLY and any( + posixpath.basename(a) in ("make", "gmake") for a in args): + raise ni.Failure(f"{where}: cannot follow the make in `{command}`; run `make ` itself") + if base in PACKAGE_RUNNERS: + raise ni.Failure(f"{where}: `{command}` runs what a package manifest says; run the script itself") + if base == "cargo" and first in CARGO_BUILDS and not (wd or after_cd) and ( + {"--workspace", "--all"} & set(args) or not any( + a in ("-p", "--package", "--manifest-path") or a.startswith(("--package=", "--manifest-path=")) + or (a.startswith("-p") and not a.startswith("--")) for a in args)): + raise ni.Failure(f"{where}: `{command}` builds crates it does not name; name each with -p") + if name in ("cd", "pushd"): + after_cd = True + elif base in ("make", "gmake"): + makes.append(make_command(args, wd or after_cd, command, where)) + elif base in INTERPRETERS: + if base in ("python", "python3", "py") and "-m" in args: + raise ni.Failure(f"{where}: cannot tell which file `{command.strip()}` runs; run the file itself") + if base in SHELLS and "-c" in args: + code = args[args.index("-c") + 1] if args.index("-c") + 1 < len(args) else "" + after_cd = walk(code, wd, where, files, guesses, makes, after_cd) + continue + if any(a in INLINE_CODE[base] for a in args): + continue + script_arg, skip_value = None, False + for arg in args: + if skip_value: + skip_value = False + elif arg in VALUE_OPTIONS: + skip_value = True + elif not arg.startswith(("-", "+")): + script_arg = arg + break + if script_arg is None or is_dynamic(script_arg) or is_absolute(script_arg): + continue + if after_cd: + raise ni.Failure(f"{where}: runs `{command.strip()}` after `cd`; give the step a working-directory instead") + path = ni.norm(posixpath.join(wd, script_arg)) + if looks_like_file(script_arg): + files.add(path) + else: + guesses.append((f"{where}: `{command.strip()}`", path)) + elif "/" in name and not is_absolute(name) and not is_dynamic(name): + if after_cd: + raise ni.Failure(f"{where}: runs `{name}` after `cd`; give the step a working-directory instead") + files.add(ni.norm(posixpath.join(wd, name))) + return after_cd + + +def make_command(args, moved, command, where): + """([targets], [VAR=value]) of `make [-jN] [VAR=value] ` from the repo root.""" + if moved or any(re.match(r"^(-C|-f|--directory|--file|--makefile)", a) for a in args): + raise ni.Failure(f"{where}: only `make ` from the repo root is followed: `{command.strip()}`") + targets, variables, i = [], [], 0 + while i < len(args): + arg = args[i] + if arg in ("-j", "-l") and i + 1 < len(args) and re.match(r"^\d+$", args[i + 1]): + i += 1 + elif "=" in arg and not arg.startswith("-"): + variables.append(arg) + elif not arg.startswith("-"): + targets.append(arg) + i += 1 + if not targets: + raise ni.Failure(f"{where}: name the targets of `{command.strip()}`, so what it runs can be followed") + return targets, variables + + +def make_environment(makefile, variables): + """The variables a Makefile's commands can take from the environment: those it reads but never + sets (a function's own, `$(call f,x)`'s $(1) and $(foreach x,...)'s x, are set, as are a + target's own, `t: X := y`, and `define X`), and its `?=` defaults where they make a path.""" + makefile = makefile.replace("$$", "") + # Not a recipe's (tab-indented) shell assignment, which sets nothing for make. + assignment = r"(?:export[ \t]+|override[ \t]+)?([A-Za-z_][\w.-]*)[ \t]*(?::{1,3}=|\+=|\?=|=)" + set_here = set(re.findall(r"^(?!\t)[ ]*" + assignment, makefile, re.M)) + set_here |= set(re.findall(r"^(?!\t)[^:=#\n]+:(?!=)[ \t]*" + assignment, makefile, re.M)) + set_here |= set(re.findall(r"^define\s+([A-Za-z_][\w.-]*)", makefile, re.M)) + set_here |= {v.split("=", 1)[0] for v in variables} | set(re.findall(r"\$\(foreach\s+([\w.-]+)\s*,", makefile)) + defaults = set(re.findall(r"^\s*([A-Za-z_][\w.-]*)\s*\?=", makefile, re.M)) + found = [] + # $(X), ${X}, $(X:a=b) and $X. + for m in re.finditer(r"\$[({]([A-Za-z_][\w.-]*)(?=[:)}])|\$([A-Za-z_])", makefile): + name = m.group(1) or m.group(2) + if name not in set_here and name not in ("MAKE", "MAKEFLAGS", "MAKECMDGOALS", "SHELL"): + found.append(name) + for name in defaults: + # Next to a path's characters: `dir/$(X)`, `$(X)/lib.a`, `$(X).mk`, `$(X)-out`. + if re.search(rf"[\w./-]\$[({{]{re.escape(name)}[)}}]|\$[({{]{re.escape(name)}[)}}][\w./-]", makefile): + found.append(name) + return sorted(set(found)) + + +def make_commands(rev, targets, variables): + """What `make -n` runs, with the commit's Makefile and no inherited variables. A Makefile that + can run other commands than it prints (conditionals, includes, $(shell)), that names the dir + make runs in, or whose commands the environment can change, is refused.""" + makefile = ni.show(rev, "Makefile") + if re.search(r"^\s*(ifeq|ifneq|ifdef|ifndef|-?include|sinclude)\b|^[^#\n]*!=" + r"|\$[({](shell|origin|wildcard|realpath|abspath|CURDIR)\b", makefile, re.M): + raise ni.Failure("the Makefile has conditionals, includes, $(shell) or paths of the dir make runs " + "in: `make -n` cannot show what a job runs") + for name in make_environment(makefile, variables): + raise ni.Failure(f"the Makefile reads {name} from the environment, which `make -n` does not see: set " + f"it in the Makefile (with =, or ?= where it names no path) or pass it as {name}=...") + with tempfile.TemporaryDirectory() as tmp: + try: + result = subprocess.run(["make", "-n", "-f", "-", *variables, *targets], input=makefile.encode(), + cwd=tmp, capture_output=True, env={"PATH": os.environ.get("PATH", "")}) + except FileNotFoundError: + raise ni.Failure("the job runs make, and make is not installed") + output = result.stdout.decode("utf-8").replace("\r", "") + if os.path.basename(tmp) in output: + raise ni.Failure(f"make -n {' '.join(targets)} prints the dir it ran in, so what it runs cannot be followed") + if result.returncode != 0: + raise ni.Failure(f"make -n {' '.join(targets)}: {result.stderr.decode(errors='replace').strip()}") + return output + + +def named_crates(rev, corpus): + """The members the text names by package name, as a word of its own (`-p canvas-ios`, not + packages/canvas/src-native/canvas-android), or by dir, after any prefix (`$ROOT/crates/x`).""" + _, names, _, _ = ni.crate_meta(rev) + return {member for name, member in names.items() + if re.search(rf"(?)", re.S) +# Where a file sets a variable to a path: a shell assignment anywhere on a line, CMake's set(), and +# get_filename_component() with DIRECTORY, whose value is the dir above the path it is given. +SHELL_SET = re.compile(r"(?:^|[\s;&|()])(?:export\s+|local\s+|readonly\s+|declare\s+)?([A-Za-z_]\w*)=" + r"(\"[^\"]*\"|'[^']*'|[^\s;&|()]*)") +CMAKE_SET = re.compile(r"^\s*(set|get_filename_component)\(\s*([A-Za-z_]\w*)\s+\"?([^\s\")]+)", re.I) +# A variable: ${{ }}, then the named forms (`${X}`, `$(X)`, `$X`), then any other (Ruby's #{x} too). +VARIABLE = re.compile(r"\$\{\{[^}]*\}\}|\$\{([A-Za-z_]\w*)\}|\$\(([A-Za-z_]\w*)\)|\$([A-Za-z_]\w*)" + r"|\$\{[^}]*\}|\$\([^)]*\)|#\{[^}]*\}|@[A-Za-z_]\w*@|%[A-Za-z_]\w*%") +# A shell's `cd`/`pushd` and where to. +CD = re.compile(r"(?:^|[\s;&|(])(?:cd|pushd)\s+(\"[^\"]*\"|'[^']*'|[^\s;&|)]+)") +TOKEN = re.compile(r"[^\s'\"`=;,(){}<>\[\]|&:!]*/[^\s'\"`=;,(){}<>\[\]|&:!]*") +# A path given as its segments: path.join(root, 'apps', 'demo'), os.path.join(ROOT, "x"). +JOIN = re.compile(r"\b(?:join|resolve)\(([^()]*)\)") +WILD = "\x01" +WILDS = r"[*?" + WILD + "]" + + +@functools.lru_cache(maxsize=None) +def blobs(rev): + """{path: (id, size)} of every tracked file at rev.""" + out = {} + for record in ni.git("ls-tree", "-r", "-l", "-z", rev).split("\0"): + if record: + meta, path = record.split("\t", 1) + _, kind, oid, size = meta.split() + if kind == "blob": + out[path] = (oid, int(size)) + return out + + +@functools.lru_cache(maxsize=None) +def texts(rev): + """{path: text} of every tracked text file at rev up to LIMIT.""" + ids = {p: oid for p, (oid, size) in blobs(rev).items() if size <= LIMIT} + missing = sorted({oid for oid in ids.values() if oid not in BLOBS}) + data = ni.git("cat-file", "--batch", data="".join(oid + "\n" for oid in missing).encode(), binary=True) + i = 0 + for oid in missing: + end = data.index(b"\n", i) + size = int(data[i:end].split()[2]) + blob = data[end + 1:end + 1 + size] + i = end + 2 + size + BLOBS[oid] = None if b"\0" in blob[:8000] else blob.decode("utf-8", errors="replace").replace("\r", "") + return {p: BLOBS[oid] for p, oid in ids.items() if BLOBS[oid] is not None} + + +BLOBS = {} # each blob's text, None for a binary, kept across revs +MATCHED = {} # by rev, the paths each pattern with a glob or variable matches + + +def code(text, p): + """The file's text without its comments, by the kind of file p is (whole, for a kind whose + comments are not known: a path read for one is the safe mistake); None for prose.""" + name = posixpath.basename(p) + ext = posixpath.splitext(name)[1] + if PROSE_NAMES.match(name) or (ext.lower() in PROSE and name not in HASH_NAMES): + return None + syntax = (C_COMMENT if ext in C_LIKE or ext.lower() in C_LIKE else XML_COMMENT if ext.lower() in XML + else HASH_COMMENT if ext.lower() in HASH or name in HASH_NAMES else None) + return text if syntax is None else syntax.sub(lambda m: " " if m.group(1) else m.group(0), text) + + +def expand(text, values): + """The text with each variable the file sets replaced by each of its values in turn, and any + other variable (a matrix value too) by WILD.""" + m = VARIABLE.search(text) + if m is None: + return [text] + rests = expand(text[m.end():], values) + name = m.group(1) or m.group(2) or m.group(3) + options = (values.get(name) if name else None) or [WILD] + if len(options) * len(rests) > 64: + options = [WILD] + return [text[:m.start()] + option + rest for option in options for rest in rests] + + +def resolve_token(token, here, entries, matched): + """The tracked files and dirs a path in a file can name: from the repo or the file's dir, with + WILD and globs standing for one segment. A path that goes up (`..`), or starts at a dir the file + does not name (an unknown variable, or `"/../x"` after env!("CARGO_MANIFEST_DIR") or the like), + may start from any dir above the file, and after an unknown dir, the `..` may lead anywhere. A + computed name that matches nothing names its dir.""" + if token.startswith("/.."): + token = WILD + token + unknown = token.startswith(WILD + "/") + token = re.sub(r"^(" + WILD + r"/)+", "", token).rstrip(".") + if token.startswith("/") or "//" in token: + return set() + segments = [s for s in token.split("/") if s] + if not any(re.search(r"[A-Za-z]", s) and not re.search(WILDS, s) for s in segments): + return set() + bases = ["", here] + if unknown or segments[0] == "..": + bases += [here.rsplit("/", n)[0] for n in range(1, here.count("/") + 1)] + forms = [segments] + if unknown and segments[0] == "..": + forms.append(segments[next(i for i, s in enumerate(segments) if s != ".."):]) + found = set() + for base, form in ((b, f) for b in bases for f in forms): + try: + path = ni.norm(posixpath.join(base, *form)) + except ni.Failure: + continue + if not re.search(WILDS, path): + if path in entries: + found.add(path) + continue + parts = path.split("/") + if path not in matched: + pattern = re.compile("^" + "/".join("[^/]*".join(map(re.escape, re.split(WILDS + "+", s))) for s in parts) + "$") + matched[path] = {p for p in entries if pattern.match(p)} + literal = "/".join(parts[:next(i for i, s in enumerate(parts) if re.search(WILDS, s))]) + found |= matched[path] or ({literal} if literal in entries else set()) + return found + + +def names(text, here, entries, matched=None): + """The tracked files and dirs the text's paths name (see resolve_token), with matched a cache + for the tree entries come from.""" + matched = {} if matched is None else matched + return set().union(*(resolve_token(token, here, entries, matched) for token in path_tokens(text))) + + +@functools.lru_cache(maxsize=None) +def path_tokens(text): + """The paths the text names, but the values it sets variables to, with the variables it sets + expanded, and each relative path also from the dir the text has `cd` to. The text is code: its + comments already gone.""" + values, found, cwd = {}, set(), None + + def define(name, value): + # A value that is not a plain path (a command's output, say) is unknown. + values.setdefault(name, []) + values[name] += [v if re.match(r"^[\w./@+" + WILD + "-]*$", v) else WILD + for v in expand(value.strip("'\""), values) if v not in values[name]] + + for line in text.split("\n"): + cmake = CMAKE_SET.match(line) + if cmake: + define(cmake.group(2), cmake.group(3) + ("/.." if cmake.group(1).lower() != "set" else "")) + continue + for m in SHELL_SET.finditer(line): + define(m.group(1), m.group(2)) + dirs = [cwd] + cd = CD.search(line) + if cd and cd.group(1).strip("'\"") != "-": + to = expand(cd.group(1).strip("'\""), values)[0] + to = to if re.match(r"^[\w./@+" + WILD + "-]*$", to) else WILD + cwd = to if cwd is None or to.startswith(("/", WILD)) else posixpath.join(cwd, to) + dirs.append(cwd) + for expanded in expand(SHELL_SET.sub(" ", line), values): + tokens = TOKEN.findall(expanded) + for m in JOIN.finditer(expanded): + args = [a.strip() for a in m.group(1).split(",")] + tokens.append("/".join(a[1:-1] if len(a) > 1 and a[0] == a[-1] and a[0] in "'\"" else WILD for a in args)) + found.update(tokens) + found.update(posixpath.join(d, t) for d in dirs if d for t in tokens if not t.startswith(("/", WILD))) + return tuple(sorted(found)) + + +@functools.lru_cache(maxsize=None) +def named_paths(rev, p): + text = code(texts(rev)[p], p) + return frozenset() if text is None else frozenset( + names(text, posixpath.dirname(p), ni.tree_entries(rev), MATCHED.setdefault(rev, {}))) + + +@functools.lru_cache(maxsize=None) +def files_under(rev): + under = collections.defaultdict(list) + for p, (kind, _) in ni.tree_entries(rev).items(): + d = posixpath.dirname(p) if kind != "tree" else None + while d: + under[d].append(p) + d = posixpath.dirname(d) + return under + + +def crate_of(rev, p): + return next((d for d in sorted(ni.crate_meta(rev)[2], key=len, reverse=True) if p.startswith(d + "/")), None) + + +def crossings(artifact, rev, wanted, source, here, targets): + """The targets that source names and the artifact's key leaves out, but source itself and the + dirs it is in, and NOT_READ's. A crate dir counts when it is outside the closure, unless a + Cargo.toml names it (cargo metadata reads those).""" + entries, under, problems = ni.tree_entries(rev), files_under(rev), [] + crate_dirs, crates = ni.crate_meta(rev)[2], ni.closure(rev, ni.ARTIFACTS[artifact].get("crates", [])) + for target in sorted(targets): + if (target == source or target.startswith(".github/workflows/") or here == target + or here.startswith(target + "/") or not_read(source, target)): + continue + if target in crate_dirs: + if target not in crates and posixpath.basename(source) != "Cargo.toml": + problems.append(f"{artifact}: {source} names the crate {target}, which is outside its crates' " + f"closure; if its job does not read it there, add it to NOT_READ with the reason") + continue + left_out = [f for f in (under[target] if entries[target][0] == "tree" else [target]) if not wanted(f)] + if left_out: + first, crate = left_out[0], crate_of(rev, left_out[0]) + whose = (f"{crate} is outside its crates' closure" if crate and crate not in crates else + f"OWNERS gives {first} to {', '.join(ni.owners(first)) or 'no artifact'}") + what = target if left_out == [target] else f"{len(left_out)} of the files under {target}" + problems.append(f"{artifact}: {source} names {what}, which its key leaves out ({whose}); if its " + f"job does not read it there, add it to NOT_READ with the reason") + return problems + + +def scan(artifact, rev, wanted): + """The paths that the text files in the artifact's key name and its key leaves out, and the files + in it too large to read that are not binaries. The job pass reads the workflows, actions and + Makefile for what the job runs of them.""" + tested = set(ni.ARTIFACTS[artifact].get("crates", [])) if artifact in CARGO_TESTS else set() + problems = [f"{artifact}: {p} is in its key but too large to scan for paths; if it is not text, add its " + f"type to BINARY" for p, (_, size) in sorted(blobs(rev).items()) + if size > LIMIT and wanted(p) and not p.lower().endswith(BINARY)] + for p in sorted(texts(rev)): + if p.startswith(".github/") or p == "Makefile" or not wanted(p): + continue + crate = crate_of(rev, p) + if crate and p[len(crate) + 1:].split("/")[0] in ("tests", "benches", "examples") and crate not in tested: + continue + problems += crossings(artifact, rev, wanted, p, posixpath.dirname(p), named_paths(rev, p)) + return problems diff --git a/tools/tests/native_check/wiring.py b/tools/tests/native_check/wiring.py new file mode 100644 index 000000000..bc19c9b05 --- /dev/null +++ b/tools/tests/native_check/wiring.py @@ -0,0 +1,206 @@ +"""Checks that every native job is wired to its cache and reads no value that changes between runs +of one key. Part of tools/tests/check-native-inputs.py, whose docstring says what it checks.""" +import re + +from . import ni +from .jobs import field, sections + + +GUARD = "steps.native.outputs.hit != 'true'" +# A context in an expression, with the field it reads (`.x` or `['x']`), if any. +CONTEXT = re.compile(r"(? Date: Wed, 18 Nov 2026 03:11:42 +0800 Subject: [PATCH 05/12] ci: rebuild native outputs by hand; restore Apple outputs on Linux Canvas Native run by hand takes `fresh`, which builds every native output without restoring or saving, to check a cached one. The native-cache action says how to drop a bad entry. The jobs that restore the two xcframeworks run on ubuntu-22.04, so a hit takes no macOS runner. actions/cache uses the same version on Linux and macOS, so they restore what the macOS job saved. The cache check now reads: - every cd in a line, and pushd/popd; - exported values and CMake set() lists; - scripts run from another directory or through $GITHUB_ACTION_PATH; - -I/-L/-F flags whose path climbs with ..; - cargo --workspace and package runners in followed scripts; - git describe/log/show, which read the commit. It also refuses continue-on-error and status functions in any if, and a matrix leg that names no artifact. --- .github/actions/native-cache/action.yml | 6 +- .github/workflows/build-native.yml | 9 +- .github/workflows/npm_release.yml | 7 +- .github/workflows/pull-request.yml | 12 +++ tools/tests/check-native-inputs.py | 124 ++++++++++++------------ tools/tests/native_check/jobs.py | 55 +++++++++-- tools/tests/native_check/paths.py | 121 +++++++++++++++++------ tools/tests/native_check/wiring.py | 12 ++- tools/tests/test_native_inputs.py | 49 ++++++++-- 9 files changed, 275 insertions(+), 120 deletions(-) diff --git a/.github/actions/native-cache/action.yml b/.github/actions/native-cache/action.yml index 05200bec6..e7b17bfae 100644 --- a/.github/actions/native-cache/action.yml +++ b/.github/actions/native-cache/action.yml @@ -5,7 +5,11 @@ description: > the week plus the hash tools/scripts/native-inputs.py computes; its docstring says what that covers and why. On a miss the job builds, and the output is saved once the job succeeds, into the scope of the ref that ran it, so pull requests can restore master's entries. With - NATIVE_CACHE_FRESH=true (the release) it neither restores nor saves, and the job builds. + NATIVE_CACHE_FRESH=true (the release, or Canvas Native run by hand with `fresh`) it neither + restores nor saves, and the job builds. + + An entry that holds a bad output stays until its week ends: delete it with `gh cache delete ` + (the job's log prints the key), or change the version in the key below to drop every entry. An output built by several jobs is restored first, in a job of its own (`restore-only`) that uploads it on a hit and skips the other jobs. On a miss they build it, and the last of them saves diff --git a/.github/workflows/build-native.yml b/.github/workflows/build-native.yml index 605a20ea3..cf30bdea5 100644 --- a/.github/workflows/build-native.yml +++ b/.github/workflows/build-native.yml @@ -114,11 +114,12 @@ jobs: # The xcframework when nothing it is built from has changed: a hit uploads it here and skips the # per-platform jobs and canvas-ios, so a lost cache entry cannot fail the run between them. A miss - # leaves canvas-ios to save it under this job's key. On macOS, as canvas-ios, for the same cache - # version. + # leaves canvas-ios to save it under this job's key. On Linux, so a hit takes no macOS runner: + # actions/cache gives Linux and macOS the same version (both zstd), so it restores what canvas-ios + # saved; were it not to, this job would only miss, and the xcframework would build every run. canvas-ios-cache: name: Canvas xcframework (cached) - runs-on: macos-15 + runs-on: ubuntu-22.04 outputs: hit: ${{ steps.native.outputs.hit }} key: ${{ steps.native.outputs.key }} @@ -269,7 +270,7 @@ jobs: # As canvas-ios-cache: a hit uploads the xcframework and skips the jobs that build it. canvas-svg-ios-cache: name: Canvas SVG xcframework (cached) - runs-on: macos-15 + runs-on: ubuntu-22.04 outputs: hit: ${{ steps.native.outputs.hit }} key: ${{ steps.native.outputs.key }} diff --git a/.github/workflows/npm_release.yml b/.github/workflows/npm_release.yml index 827e826e0..fdde00d3d 100644 --- a/.github/workflows/npm_release.yml +++ b/.github/workflows/npm_release.yml @@ -117,9 +117,10 @@ jobs: # Master's Canvas Native runs upload artifacts under the same names, but theirs can be # cached outputs of any age, so only an npm Release run of this tag at this commit may stand - # in. Its conclusion is not checked: the usual reason to reuse a run is that its publish - # failed after the native builds succeeded, and place-native-artifacts.sh fails on any - # artifact that is missing. + # in: it ran this workflow at this commit, which builds fresh. This identifies the run; it + # cannot see how the run built. Its conclusion is not checked: the usual reason to reuse a + # run is that its publish failed after the native builds succeeded, and + # place-native-artifacts.sh fails on any artifact that is missing. - name: Check native_run_id if: inputs.native_run_id != '' env: diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 264d45f80..0b520b9da 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -17,6 +17,15 @@ on: - master pull_request: workflow_dispatch: + inputs: + fresh: + description: Build every native output instead of restoring it (to check a cached output; it saves nothing) + type: boolean + default: false + +env: + # Read by .github/actions/native-cache. + NATIVE_CACHE_FRESH: ${{ inputs.fresh }} # A pull request push cancels the run it supersedes. On master a running build finishes (it # saves the caches pull requests read) and only the newest waiting push runs after it. @@ -75,6 +84,7 @@ jobs: if: steps.native.outputs.hit != 'true' env: RUSTFLAGS: '-C link-arg=-undefined -C link-arg=dynamic_lookup' + # The marker the cache saves is the pass: written last, in the same step, after the tests. run: | cargo test -p canvas-c --features 2d,webgl,gl mkdir -p .native-cache && date -u > .native-cache/unit-tests-passed @@ -90,6 +100,8 @@ jobs: build-native: name: Build Native uses: ./.github/workflows/build-native.yml + with: + fresh: ${{ inputs.fresh == true }} npm: name: Npm Build diff --git a/tools/tests/check-native-inputs.py b/tools/tests/check-native-inputs.py index 04a231f04..3d377e953 100644 --- a/tools/tests/check-native-inputs.py +++ b/tools/tests/check-native-inputs.py @@ -1,67 +1,79 @@ #!/usr/bin/env python3 """Holds the claims tools/scripts/native-inputs.py keys the native builds by (OWNERS, ARTIFACTS and each artifact's crate closure) to what the jobs are seen to read, and checks that every cached job -is wired to its cache. Static Checks runs it. +is wired to its cache. Static Checks runs it. Its parts are in native_check: jobs.py reads the jobs, +paths.py scans the keys, wiring.py checks the wiring and the values that vary between runs. check-native-inputs.py [REV] REV defaults to HEAD -A key leaves out only what OWNERS places elsewhere, the crates outside its closure, the other jobs' -blocks and the actions its job does not use, so a job can read what its key misses only across one -of those lines. Two passes look for reads across them. - -Reading the job: its steps and job-level keys, its actions' steps, the files they run and the files -those mention, what `make -n` prints for the targets it runs, and the scripts in the package dirs -OWNERS gives the artifact, followed in turn. It fails when a file read that way is outside the key, -a crate named that way (by package name or dir) is outside the closure, or the job cannot be read: -a file run that is not tracked, a file run after `cd`, a path above the repo, a script argument -(`bash build`) that is no file, `python -m`, a package runner, cargo building crates it does not -name, an unclosed quote or heredoc, a value continued on plain lines, `make` in any form but -`make [-jN] [VAR=x] ` from the repo root, a Makefile with conditionals, includes, $(shell) -or paths of the dir it runs in, a Makefile that reads a variable it does not set (or a `?=` -default in a path), which the environment would choose, a followed script that runs make (but the -third-party builds in OWN_MAKE) or sources a computed path, a local action without action.yml, a -workflow key after `jobs:`, a YAML anchor or alias, or a workflow- or job-wide working-directory. +It is a lint, not a proof. A key leaves out only what OWNERS places elsewhere, the crates outside +its closure, the other jobs' blocks and the actions its jobs do not use, so a job can read what its +key misses only across one of those lines, and two passes look for reads across them; a read +written in a form neither pass follows goes unseen. So OWNERS claims that leave files out are kept +narrow, and a file no rule places is in every key. + +Reading the job: its steps and job-level keys, its actions' steps (with $GITHUB_ACTION_PATH as the +action's dir), the files they run and the files those mention, what `make -n` prints for the +targets it runs, and the scripts in the package dirs OWNERS gives the artifact, followed in turn. +In a job whose legs build different artifacts, matrix values are this artifact's legs' (the item of +a list of maps that names it in the native-cache `artifact:`). It fails when a file read that way +is outside the key, a crate named that way (by package name or dir) is outside the closure, or the +job cannot be read: a file run that is not tracked, a file a step runs after `cd`, a path above the +repo, a script argument (`bash build`) that is no file, `python -m`, a package runner, cargo +building crates it does not name (these four in followed shell scripts too), an unclosed quote or +heredoc, a value continued on plain lines, `make` in any form but `make [-jN] [VAR=x] ` +from the repo root, a Makefile with conditionals, includes, $(shell) or paths of the dir it runs +in, a Makefile that reads a variable it does not set (or a `?=` default in a path), which the +environment would choose, a followed script that runs make (but the third-party builds in OWN_MAKE) +or sources a computed path inside the repo, a matrix list over several lines, a local action +without action.yml, a workflow key after `jobs:`, a YAML anchor or alias, or a workflow- or +job-wide working-directory. Scanning the key: every text file in the key but prose (docs, notices, git's own files), the -workflows, actions and Makefile, and the step and job-key text the first pass reads, are searched -for paths that lead out of the key. A path counts relative to the repo or to the file's dir, and -when it goes up (`..`), from any dir above the file; after a variable the file sets (`set(DIR -...)`, `DIR=...`), with each of its values; after any other variable (`${CMAKE_CURRENT_SOURCE_DIR}`, -`env!("CARGO_MANIFEST_DIR")` with `"/../x"`), from any of those dirs, with or without the `..` -after it; with a glob or another variable (a matrix value too) standing for one path segment, or -for the dir it is in when that matches nothing; given as the segments of a join() or resolve() -call; and naming a dir, for every file under it, or a crate dir outside the closure (but in a -Cargo.toml, which cargo metadata reads). Comments, by each kind of file's syntax, and the values -variables are set to are not paths. In a job whose legs build different artifacts, a path made with -a matrix value counts when no artifact of the job reads it. Crates' tests, benches and examples -count only for the jobs in CARGO_TESTS, which run `cargo test`. A file in the key over 2 MB must be -of a binary type (BINARY). This pass holds the claims about build files, such as the C++ the -Android CMake builds compile from the iOS package dir. - -A path a file names but its job does not read there (one it writes, say) is listed in NOT_READ with -the reason, for both passes. +workflows, action manifests and Makefile, and the step and job-key text the first pass reads (and +a followed script from the dir a step runs it in), are searched for paths that lead out of the +key. A path counts relative to the repo or to the file's dir, and when it goes up (`..`), from any +dir above the file; from every dir the text has `cd` to; after a variable the file sets +(`set(DIR ...)`, `DIR=...`), with each of its values; after any other variable +(`${CMAKE_CURRENT_SOURCE_DIR}`, `env!("CARGO_MANIFEST_DIR")` with `"/../x"`), from any of those +dirs, with or without the `..` after it; after a compiler flag (`-I`, `-L`, `-F`); with a glob or +another variable (a matrix value too) standing for one path segment, or for the dir it is in when +that matches nothing; given as the segments of a join() or resolve() call; in the values of a +CMake set() list or an exported shell variable; and naming a dir, for every file under it, or a +crate dir outside the closure (but in a Cargo.toml, which cargo metadata reads). In shell text, a +bare word given to a reading command (`ls apps`) is a path, and what a line only writes (the +arguments of mkdir, rm and touch, the destination of cp and the like, a redirection's target) or +prints (echo without a redirection) is not. Comments, by each kind of file's syntax, are not +paths. Crates' tests, benches and examples count only for the jobs in CARGO_TESTS, which run +`cargo test`. A text file in the key over 2 MB fails, as it cannot be scanned. This pass holds the +claims about build files, such as the C++ the Android CMake builds compile from the iOS package dir. + +A path a file names but its job does not read there is listed in NOT_READ with the reason, for both +passes. Both fail on values that differ between runs that share a key: a ${{ }} context other than matrix, steps, env, strategy, runner and github.workspace, in any case and in `.` or `[ ]` form, in the workflow's settings, the job's keys, its build steps and its actions' steps (where `inputs.` is the -job's own `with:`), and the run's GITHUB_ variables (GITHUB_SHA, GITHUB_REF, ...) in the text the -first pass reads. +job's own `with:`), the run's GITHUB_ variables (GITHUB_SHA, GITHUB_REF, ...) and git commands that +read the commit, in the text the first pass reads. And the wiring: each job that uploads an artifact in build-native.yml is one of an artifact's, and each artifact's first job restores it: a native-cache step with `id: native` right after the checkout, for its own artifact and the upload's path, with `variant: ${{ toJSON(matrix) }}` in a -matrix job, and every later step but the upload skipped on a hit (its `if:` is -`steps.native.outputs.hit != 'true'`, or that && more, with no ||). An artifact built by several -jobs (the xcframeworks) has a first job that restores it with `restore-only: 'true'`, only uploads -it on a hit, and has the step's `hit` and `key` as outputs. Its other jobs need the first and have -`if: needs..outputs.hit != 'true'` (or that && more, with no ||), and the last of them -restores it as above, with `key: ${{ needs..outputs.key }}`, and saves it. For the reader, -a make target made of a matrix value counts once per value the strategy lists. +matrix job, every later step but the upload skipped on a hit (its `if:` is +`steps.native.outputs.hit != 'true'`, or that && more, with no ||), and one upload, under its +artifact's name. An artifact built by several jobs (the xcframeworks) has a first job that restores +it with `restore-only: 'true'`, only uploads it on a hit, and has the step's `hit` and `key` as +outputs. Its other jobs need the first and have `if: needs..outputs.hit != 'true'` (or that +&& more, with no ||), and the last of them needs every other and restores it as above, with `key: +${{ needs..outputs.key }}`, and saves it. No job of an artifact has a status function in an +`if:` or continue-on-error, which run on after a failure and save what is left. No local action's +descriptions hold `${{ }}`, which stop the runner loading it. For the reader, a make target made of +a matrix value counts once per value the strategy lists. Needs git, Python 3.8+, cargo and make. """ import argparse -import functools import os import re import sys @@ -70,9 +82,9 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the parts, however this is loaded from native_check import ni # noqa: E402 -from native_check.jobs import apart, discover, each_leg, named_crates # noqa: E402 +from native_check.jobs import discover, each_leg, named_crates # noqa: E402 from native_check.paths import CARGO_TESTS, MATCHED, code, crossings, names, not_read, scan # noqa: E402 -from native_check.wiring import RUN_VARIABLE, check_wiring, expressions, moves_cache, varying # noqa: E402 +from native_check.wiring import READS_COMMIT, RUN_VARIABLE, check_wiring, expressions, moves_cache, varying # noqa: E402 @@ -92,29 +104,21 @@ def check_reads(artifact, rev): f"add it to CARGO_TESTS") for name in sorted(set(RUN_VARIABLE.findall(corpus))): problems.append(f"{artifact}: its job reads GITHUB_{name}, which can change between runs that share a key") + if READS_COMMIT.search(corpus): + problems.append(f"{artifact}: its job reads the commit ({READS_COMMIT.search(corpus).group(0)}), which can " + f"change between runs that share a key") for manifest, step in action_steps: if not moves_cache(step): for context in varying(expressions([], [step]), in_action=True): problems.append(f"{artifact}: {manifest} uses {context}, which can change between runs that share a key") - # A path made with a matrix value is one leg's: in a job whose legs build different artifacts - # (the variant keys each leg), it counts when no artifact of the job reads it. Any other path - # counts against this artifact's key. + # Matrix values are this artifact's legs' (see discover), so every path counts against its key. entries, cache = ni.tree_entries(rev), MATCHED.setdefault(rev, {}) for read in texts_read: - legs = [a for a in ni.ARTIFACTS if read.job in ni.jobs_of(a)] if read.job else [artifact] - filters = [key_filter(a, rev) for a in legs] - plain, made = apart(read.text) - for text, wants in ((plain, wanted), (each_leg(made, read.values), lambda p: any(f(p) for f in filters))): - found = names(code(text, "step.yml"), read.wd, entries, cache) - set(reads) - problems += crossings(artifact, rev, wants, read.where, read.wd, found) + found = names(code(each_leg(read.text, read.values), "step.yml"), read.wd, entries, cache, shell=True) + problems += crossings(artifact, rev, wanted, read.where, read.wd, found - set(reads)) return problems + scan(artifact, rev, wanted) -@functools.lru_cache(maxsize=None) -def key_filter(artifact, rev): - return ni.key_filter(artifact, rev) - - def main(argv): parser = argparse.ArgumentParser(prog="check-native-inputs.py", description="hold the native cache keys to what their jobs read") diff --git a/tools/tests/native_check/jobs.py b/tools/tests/native_check/jobs.py index aac334893..18d9ea7cf 100644 --- a/tools/tests/native_check/jobs.py +++ b/tools/tests/native_check/jobs.py @@ -202,14 +202,16 @@ def is_absolute(token): return token.startswith(("/", "~")) or re.match(r"^[A-Za-z]:/", token) is not None -def matrix_values(strategy): +def matrix_values(strategy, artifact=None, named=""): """{key: [values]} of the values a job's strategy lists for each matrix key: `platform: [ios, - tvos]`, a list of scalars, a list of maps (`module.name`), and include's maps (their own keys).""" + tvos]`, a list of scalars, a list of maps (`module.name`), and include's maps (their own keys). + With an artifact, and named the job's native-cache `artifact:` (`${{ matrix.module.name + }}-windows`), a list of maps keeps only the item that names the artifact: its legs' values.""" lines = [l for l in strategy if l.strip()] start = next((i for i, l in enumerate(lines) if re.match(r"^\s+matrix:\s*$", l)), None) if start is None: return {} - values, key, column = {}, None, None + values, items, key, column = {}, {}, None, None for line in lines[start + 1:]: if ni.indent(line) <= ni.indent(lines[start]): break @@ -230,11 +232,24 @@ def matrix_values(strategy): if dash and not name: values.setdefault(key, []).append(value.strip("'\"")) continue + if dash: + items.setdefault(key, []).append({}) field_key = name if key == "include" else f"{key}.{name}" if value and not value.startswith(("[", "{")): values.setdefault(field_key, []) if value.strip("'\"") not in values[field_key]: values[field_key].append(value.strip("'\"")) + if key in items: + items[key][-1][name] = value.strip("'\"") + for key, maps in items.items(): + own = [m for m in maps if artifact and key != "include" and re.sub( + r"\$\{\{\s*matrix\." + re.escape(key) + r"\.([\w-]+)\s*\}\}", lambda x: m.get(x.group(1), "\x00"), named) == artifact] + if len(own) == 1: + for name in {name for m in maps for name in m}: + if name in own[0]: + values[f"{key}.{name}"] = [own[0][name]] + else: + values.pop(f"{key}.{name}", None) return values @@ -306,7 +321,10 @@ def unwrap(tokens): return tokens -def walk(script, wd, where, files, guesses, makes, after_cd): +def walk(script, wd, where, files, guesses, makes, after_cd, followed=False): + """What shell text runs, into files, guesses and makes, with the refusals in the docstring. A + followed script is held to the same refusals but may `cd` (the scan follows it); what it runs + is found by its mentions.""" for tokens in shell_commands(script, where): command = " ".join(tokens) tokens = unwrap(tokens) @@ -321,13 +339,20 @@ def walk(script, wd, where, files, guesses, makes, after_cd): raise ni.Failure(f"{where}: cannot follow the make in `{command}`; run `make ` itself") if base in PACKAGE_RUNNERS: raise ni.Failure(f"{where}: `{command}` runs what a package manifest says; run the script itself") - if base == "cargo" and first in CARGO_BUILDS and not (wd or after_cd) and ( - {"--workspace", "--all"} & set(args) or not any( + # --workspace builds crates no one names wherever it runs; without -p, cargo builds the + # crate of the dir it runs in, which only a cd or working-directory can name. + if base == "cargo" and first in CARGO_BUILDS and ({"--workspace", "--all"} & set(args) or ( + not (wd or after_cd) and not any( a in ("-p", "--package", "--manifest-path") or a.startswith(("--package=", "--manifest-path=")) - or (a.startswith("-p") and not a.startswith("--")) for a in args)): + or (a.startswith("-p") and not a.startswith("--")) for a in args))): raise ni.Failure(f"{where}: `{command}` builds crates it does not name; name each with -p") if name in ("cd", "pushd"): after_cd = True + elif followed: + if base in ("python", "python3", "py") and "-m" in args: + raise ni.Failure(f"{where}: cannot tell which file `{command.strip()}` runs; run the file itself") + if base in SHELLS and "-c" in args and args.index("-c") + 1 < len(args): + after_cd = walk(args[args.index("-c") + 1], wd, where, files, guesses, makes, after_cd, followed) elif base in ("make", "gmake"): makes.append(make_command(args, wd or after_cd, command, where)) elif base in INTERPRETERS: @@ -491,8 +516,10 @@ def take(step, step_where, scan, values=None, job=None): if re.match(r"^\s*(?:-\s+)?working-directory:", line): raise ni.Failure(f"{where}: job-wide working-directory: {line.strip()}") # A matrix names every leg's values, each leg reads its own, and its key has them (variant). + # In a job whose legs build different artifacts, the values are this artifact's legs'. matrix = sections(outside, 4, {"strategy"}) - values = matrix_values(matrix) + cache = next((s for s in steps if re.search(r"uses:\s*\./\.github/actions/native-cache\b", "\n".join(s))), []) + values = matrix_values(matrix, artifact, field(cache, "artifact")) texts_read.append(Read(f"{where} job keys", (path, job_id), "\n".join(l for l in outside if l not in matrix), "", values)) for p in mentions("\n".join(outside), [], tree): reach(p, f"{where} job keys") @@ -527,6 +554,8 @@ def take(step, step_where, scan, values=None, job=None): # A JavaScript or Docker action's code lives in its dir, which is in the key whole. if any(re.match(r"^\s+using:\s*['\"]?composite", l) for l in lines[runs:]): for step in ni.steps_of("\n".join(lines[runs:]), 2, manifest)[1]: + # The action's own dir, as the runner gives it. + step = [re.sub(r"\$\{\{\s*github\.action_path\s*\}\}|\$\{?GITHUB_ACTION_PATH\}?", p, l) for l in step] take(step, manifest, p != SKIA_CACHE) action_steps.append((manifest, step)) continue @@ -549,14 +578,20 @@ def take(step, step_where, scan, values=None, job=None): if p not in OWN_MAKE: if re.search(r"^\s*(?:\S*/)?g?make\s", text, re.M): raise ni.Failure(f"{p} runs make; run make from the job instead") - for m in re.finditer(r"^\s*(?:source|\.)\s+(\S+)", text, re.M): + # A file sourced from outside the repo ($HOME/.cargo/env) is not one of its inputs. + for m in re.finditer(r"(?:^|[;&|(])\s*(?:source|\.)\s+(\S+)", text, re.M): source = SCRIPT_DIR_REF.sub("@", WORKSPACE_PREFIX.sub("", m.group(1).strip("'\""))) - if is_dynamic(source): + if is_dynamic(source) and not re.match(r"^(\$\{?HOME\b|~|/)", source): raise ni.Failure(f"{p}: cannot tell which file `{m.group(0).strip()}` reads") + if p.endswith((".sh", ".bash", ".zsh")) or (p in executed and "." not in posixpath.basename(p)): + walk(text, "", p, set(), [], [], False, followed=True) corpus.append(text) here = posixpath.dirname(p) for found in mentions(text, [wd_of.get(p, ""), here], tree, here): reach(found, p, wd_of.get(p, "")) + # Run from another dir, its relative paths are read from there too. + if wd_of.get(p, "") not in ("", here): + texts_read.append(Read(p, None, text, wd_of[p], {})) return reads, "\n".join(corpus), action_steps, texts_read diff --git a/tools/tests/native_check/paths.py b/tools/tests/native_check/paths.py index 5d78523fc..67a35d6a9 100644 --- a/tools/tests/native_check/paths.py +++ b/tools/tests/native_check/paths.py @@ -14,9 +14,6 @@ # Paths that a file in a key names but that its job does not read there: (the file, as an OWNERS # rule; the whole path, where `*` stands for one segment; why). NOT_READ = [ - ("tools/scripts/build-napi.sh", "packages/*/platforms/windows/*", "it writes each module's build there"), - ("tools/scripts/build-napi.sh", "packages/*/platforms/windows/*/*", - "it writes each module's build, and ANGLE's DLLs beside canvas's"), ("tools/scripts/download-v8.sh", "packages/canvas/src-native/canvas-android/canvas/src/main/cpp/include", "it writes the V8 headers it downloads there"), ("tools/scripts/download-v8.sh", "packages/canvas/src-native/canvas-ios/CanvasNative/include", @@ -37,10 +34,6 @@ def whole(pattern): LIMIT = 2_000_000 -# Files no build reads as text over the limit: what a key holds beyond it must be one of these. -BINARY = (".node", ".aar", ".so", ".dll", ".dylib", ".a", ".lib", ".jar", ".zip", ".ogg", ".wav", ".mp3", ".mp4", - ".png", ".jpg", ".jpeg", ".webp", ".gif", ".hdr", ".exr", ".glb", ".ktx2", ".fbx", ".3mf", ".bin", ".ttf", - ".otf", ".woff", ".woff2") # How each kind of file writes comments; prose and git's own files are not read by builds. C_LIKE = (".rs", ".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".inl", ".m", ".mm", ".swift", ".kt", ".kts", ".java", ".gradle", ".groovy", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".go", ".cs", ".pbxproj", ".json5", @@ -59,9 +52,9 @@ def whole(pattern): XML_COMMENT = re.compile(r"()", re.S) # Where a file sets a variable to a path: a shell assignment anywhere on a line, CMake's set(), and # get_filename_component() with DIRECTORY, whose value is the dir above the path it is given. -SHELL_SET = re.compile(r"(?:^|[\s;&|()])(?:export\s+|local\s+|readonly\s+|declare\s+)?([A-Za-z_]\w*)=" +SHELL_SET = re.compile(r"(?:^|[\s;&|()])(export\s+|(?:local|readonly|declare)\s+(?=\w))?([A-Za-z_]\w*)=" r"(\"[^\"]*\"|'[^']*'|[^\s;&|()]*)") -CMAKE_SET = re.compile(r"^\s*(set|get_filename_component)\(\s*([A-Za-z_]\w*)\s+\"?([^\s\")]+)", re.I) +CMAKE_SET = re.compile(r"^\s*(set|get_filename_component)\(\s*([A-Za-z_]\w*)\s+\"?([^\s\")]+)\"?([^)]*)", re.I) # A variable: ${{ }}, then the named forms (`${X}`, `$(X)`, `$X`), then any other (Ruby's #{x} too). VARIABLE = re.compile(r"\$\{\{[^}]*\}\}|\$\{([A-Za-z_]\w*)\}|\$\(([A-Za-z_]\w*)\)|\$([A-Za-z_]\w*)" r"|\$\{[^}]*\}|\$\([^)]*\)|#\{[^}]*\}|@[A-Za-z_]\w*@|%[A-Za-z_]\w*%") @@ -107,6 +100,17 @@ def texts(rev): MATCHED = {} # by rev, the paths each pattern with a glob or variable matches +SHELL_FILES = (".sh", ".bash", ".zsh") + + +def textual(p): + """Whether p is of a kind of text file whose comments, or prose, this knows (or has no extension): + one too large to scan must not be skipped as if it were binary.""" + name = posixpath.basename(p) + ext = posixpath.splitext(name)[1].lower() + return not ext or name in HASH_NAMES or ext in C_LIKE + HASH + XML + PROSE + (".json", ".svg", ".csv") + + def code(text, p): """The file's text without its comments, by the kind of file p is (whole, for a kind whose comments are not known: a path read for one is the safe mistake); None for prose.""" @@ -139,6 +143,7 @@ def resolve_token(token, here, entries, matched): does not name (an unknown variable, or `"/../x"` after env!("CARGO_MANIFEST_DIR") or the like), may start from any dir above the file, and after an unknown dir, the `..` may lead anywhere. A computed name that matches nothing names its dir.""" + token = re.sub(r"^-(?:I|L|F|isystem|iquote|idirafter|include)(?=\S)", "", token) if token.startswith("/.."): token = WILD + token unknown = token.startswith(WILD + "/") @@ -173,19 +178,68 @@ def resolve_token(token, here, entries, matched): return found -def names(text, here, entries, matched=None): +def names(text, here, entries, matched=None, shell=False): """The tracked files and dirs the text's paths name (see resolve_token), with matched a cache - for the tree entries come from.""" + for the tree entries come from; shell for shell text (see path_tokens).""" matched = {} if matched is None else matched - return set().union(*(resolve_token(token, here, entries, matched) for token in path_tokens(text))) + return set().union(*(resolve_token(token, here, entries, matched) for token in path_tokens(text, shell))) + + +# Shell commands whose arguments are paths they write, not read (the last of cp-like ones'), and +# commands that read the paths given to them as bare words (`ls apps`). +WRITES_ALL = {"mkdir", "rm", "rmdir", "touch", "chmod"} +WRITES_LAST = {"cp", "mv", "install", "ln", "rsync"} +PRINTS = {"echo", "printf"} +READS = {"ls", "cat", "cp", "mv", "rsync", "tar", "zip", "find", "du", "stat", "head", "tail", "grep", "sed", "awk", + "cmp", "diff", "sha256sum", "shasum", "md5sum", "xxd", "ln", "source", ".", "bash", "sh", "zsh", "python", + "python3", "node", "file", "readlink", "realpath", "wc", "install"} + + +def shell_reads(line): + """The words of a shell line that can be paths it reads: without what it only writes (the + arguments of mkdir and the like, the destination of cp and the like, a redirection's target) or + prints (echo without a redirection), with the bare words a reading command is given marked as + paths (`./`).""" + kept = [] + for segment in re.split(r"&&|\|\||[;|]", line): + words = segment.split() + while words and re.match(r"^[A-Za-z_]\w*=", words[0]): + words = words[1:] + if not words: + continue + command = posixpath.basename(words[0].strip("'\"")) + redirected = re.search(r"(?", segment) + if command in PRINTS and not redirected: + continue + args = [w for w in words[1:]] + drop = set() + for i, w in enumerate(args): + if w in (">", ">>") and i + 1 < len(args): + drop.add(i + 1) + elif re.match(r"^>>?\S", w): + drop.add(i) + operands = [i for i, w in enumerate(args) if not w.startswith("-") and i not in drop] + if command in WRITES_ALL: + drop.update(operands) + elif command in WRITES_LAST and operands: + target = next((i + 1 for i, w in enumerate(args) if w in ("-t", "--target-directory") and i + 1 < len(args)), None) + drop.add(target if target is not None else operands[-1]) + kept.append(words[0]) + for i, w in enumerate(args): + if i in drop: + continue + bare = command in READS and not w.startswith("-") and "/" not in w and re.search(r"[A-Za-z]", w) + kept.append("./" + w.strip("'\"") if bare else w) + return " ".join(kept) @functools.lru_cache(maxsize=None) -def path_tokens(text): - """The paths the text names, but the values it sets variables to, with the variables it sets - expanded, and each relative path also from the dir the text has `cd` to. The text is code: its - comments already gone.""" - values, found, cwd = {}, set(), None +def path_tokens(text, shell=False): + """The paths the text names: its tokens with a `/` (and in shell text, the bare words a reading + command is given, without what a line only writes or prints), with the variables it sets + expanded, the values of the ones it exports and of CMake's set() lists, and each relative path + also from every dir the text has `cd` to. The text is code: its comments already gone.""" + values, found, dirs = {}, set(), [] def define(name, value): # A value that is not a plain path (a command's output, say) is unknown. @@ -193,27 +247,31 @@ def define(name, value): values[name] += [v if re.match(r"^[\w./@+" + WILD + "-]*$", v) else WILD for v in expand(value.strip("'\""), values) if v not in values[name]] - for line in text.split("\n"): + lines = re.sub(r"\\\n", " ", text).split("\n") if shell else text.split("\n") + for line in lines: cmake = CMAKE_SET.match(line) if cmake: define(cmake.group(2), cmake.group(3) + ("/.." if cmake.group(1).lower() != "set" else "")) - continue + # A list's values are what is built from (sources); one value names a dir its uses extend. + line = " ".join(cmake.group(3, 4)) if cmake.group(1).lower() == "set" and cmake.group(4).strip() else "" for m in SHELL_SET.finditer(line): - define(m.group(1), m.group(2)) - dirs = [cwd] - cd = CD.search(line) - if cd and cd.group(1).strip("'\"") != "-": + define(m.group(2), m.group(3)) + exported = " ".join(m.group(3) for m in SHELL_SET.finditer(line) if m.group(1)) + for cd in CD.finditer(line): + if cd.group(1).strip("'\"") == "-": + continue to = expand(cd.group(1).strip("'\""), values)[0] to = to if re.match(r"^[\w./@+" + WILD + "-]*$", to) else WILD - cwd = to if cwd is None or to.startswith(("/", WILD)) else posixpath.join(cwd, to) - dirs.append(cwd) - for expanded in expand(SHELL_SET.sub(" ", line), values): + # As given and from the dir before it, since a popd or subshell may have left that one. + dirs += [to] + ([posixpath.join(dirs[-1], to)] if dirs and not to.startswith(("/", WILD)) else []) + rest = SHELL_SET.sub(" ", line) + " " + exported + for expanded in expand(shell_reads(rest) if shell else rest, values): tokens = TOKEN.findall(expanded) for m in JOIN.finditer(expanded): args = [a.strip() for a in m.group(1).split(",")] tokens.append("/".join(a[1:-1] if len(a) > 1 and a[0] == a[-1] and a[0] in "'\"" else WILD for a in args)) found.update(tokens) - found.update(posixpath.join(d, t) for d in dirs if d for t in tokens if not t.startswith(("/", WILD))) + found.update(posixpath.join(d, t) for d in dirs for t in tokens if not t.startswith(("/", WILD))) return tuple(sorted(found)) @@ -221,7 +279,7 @@ def define(name, value): def named_paths(rev, p): text = code(texts(rev)[p], p) return frozenset() if text is None else frozenset( - names(text, posixpath.dirname(p), ni.tree_entries(rev), MATCHED.setdefault(rev, {}))) + names(text, posixpath.dirname(p), ni.tree_entries(rev), MATCHED.setdefault(rev, {}), p.endswith(SHELL_FILES))) @functools.lru_cache(maxsize=None) @@ -270,11 +328,10 @@ def scan(artifact, rev, wanted): in it too large to read that are not binaries. The job pass reads the workflows, actions and Makefile for what the job runs of them.""" tested = set(ni.ARTIFACTS[artifact].get("crates", [])) if artifact in CARGO_TESTS else set() - problems = [f"{artifact}: {p} is in its key but too large to scan for paths; if it is not text, add its " - f"type to BINARY" for p, (_, size) in sorted(blobs(rev).items()) - if size > LIMIT and wanted(p) and not p.lower().endswith(BINARY)] + problems = [f"{artifact}: {p} is in its key but too large to scan for paths" for p, (_, size) in sorted(blobs(rev).items()) + if size > LIMIT and wanted(p) and textual(p)] for p in sorted(texts(rev)): - if p.startswith(".github/") or p == "Makefile" or not wanted(p): + if p.startswith(".github/workflows/") or re.match(r"^\.github/actions/[^/]+/action\.ya?ml$", p) or p == "Makefile" or not wanted(p): continue crate = crate_of(rev, p) if crate and p[len(crate) + 1:].split("/")[0] in ("tests", "benches", "examples") and crate not in tested: diff --git a/tools/tests/native_check/wiring.py b/tools/tests/native_check/wiring.py index bc19c9b05..60e8a0d82 100644 --- a/tools/tests/native_check/wiring.py +++ b/tools/tests/native_check/wiring.py @@ -16,6 +16,8 @@ RUN_VARIABLE = re.compile(r"\bGITHUB_(SHA|REF|REF_NAME|REF_TYPE|REF_PROTECTED|HEAD_REF|BASE_REF|EVENT_NAME|" r"EVENT_PATH|RUN_ID|RUN_NUMBER|RUN_ATTEMPT|ACTOR|ACTOR_ID|TRIGGERING_ACTOR|WORKFLOW|" r"WORKFLOW_REF|WORKFLOW_SHA|RETENTION_DAYS)\b") +# Git commands whose output is the commit, which differs between commits that share a key. +READS_COMMIT = re.compile(r"\bgit\s+(?:describe|log|show|rev-parse\s+(?:--\S+\s+)*(?:HEAD|@)\b)") def moves_cache(step): @@ -95,6 +97,9 @@ def check_wiring(rev): if STATUS.search(condition): problems.append(f"{where}: `if: {condition.strip()}` holds a status function, which runs it after " f"what it follows failed") + # It runs what follows a failure, and saves the cache with whatever the failed step left. + if job_key(outside, "continue-on-error") or any(field(s, "continue-on-error") for s in steps): + problems.append(f"{where}: continue-on-error runs it on after a failure, and the cache saves what is left") if cache is None: continue if field(cache, "id") != "native": @@ -156,7 +161,7 @@ def check_wiring(rev): raise ni.Failure("\n ".join(["native-cache wiring:", *sorted(set(problems), key=problems.index)])) -STATUS = re.compile(r"\b(success|always|cancelled|failure)\s*\(") +STATUS = re.compile(r"\b(success|always|cancelled|failure)\s*\(", re.I) def restored(where, outside, steps, cache, uploads, uploaded): @@ -197,9 +202,10 @@ def guarded(condition, guard): def job_key(outside, name): - """A job-level key's inline value; '' when the job has none.""" + """A job-level key's value; '' when the job has none. A value continued on plain lines is an + error, as in a step.""" lines = sections(outside, 4, {name}) - return field(lines[:1], name) if lines else "" + return field(lines, name) if lines else "" def needs(outside): diff --git a/tools/tests/test_native_inputs.py b/tools/tests/test_native_inputs.py index e9d3b1948..f7f52a6b6 100644 --- a/tools/tests/test_native_inputs.py +++ b/tools/tests/test_native_inputs.py @@ -190,8 +190,8 @@ def test_relative_to_a_base_or_the_script_dir(self): "tools/assets/icons/a.png")} -def named(text, here=""): - return paths.names(text, here, ENTRIES) +def named(text, here="", shell=False): + return paths.names(text, here, ENTRIES, shell=shell) class Paths(unittest.TestCase): @@ -243,6 +243,26 @@ def test_after_a_cd(self): def test_the_words_made_of_a_matrix_value(self): self.assertEqual(jobs.apart("cp a/b x/${{ matrix.n }}/y z"), ("cp a/b z", "x/${{ matrix.n }}/y")) + def test_an_artifacts_own_leg_of_a_shared_matrix(self): + strategy = [" strategy:", " matrix:", " module:", " - name: canvas-svg", " crate: svg-napi", + " - name: audio", " crate: audio-napi", " arch: [x64, arm64]"] + self.assertEqual(jobs.matrix_values(strategy, "audio-windows", "${{ matrix.module.name }}-windows"), + {"module.name": ["audio"], "module.crate": ["audio-napi"], "arch": ["x64", "arm64"]}) + + def test_shell_writes_and_prints_are_not_reads(self): + self.assertEqual(named('mkdir -p tools/assets && cp x/y tools/assets/icons/a.png; rm -rf tools/assets\n' + 'echo tools/assets/icons/a.png; cat x > tools/assets/icons/a.png', shell=True), set()) + self.assertEqual(named("cp tools/assets/icons/a.png out; echo tools/assets >> list", shell=True), + {"tools/assets/icons/a.png", "tools/assets"}) + + def test_shell_bare_names_exports_and_lists(self): + self.assertEqual(named("ls apps; tar czf x.tgz tools", shell=True), {"apps", "tools"}) + self.assertEqual(named('export ASSETS="$PWD/tools/assets"'), {"tools/assets"}) + self.assertEqual(named("set(SRC a.c tools/assets/icons/a.png)"), {"tools/assets/icons/a.png"}) + self.assertEqual(named("pushd tools; popd; pushd apps; cp demo/audio/a.wav /tmp/x", shell=True), {"apps/demo/audio/a.wav"}) + self.assertEqual(named("OTHER_CFLAGS = -I$(SRCROOT)/../../platforms/ios/src/cpp", "packages/canvas/src-native/android"), + {"packages/canvas/platforms/ios/src/cpp"}) + def test_a_matrix_value_is_one_segment_or_each_listed_value(self): self.assertEqual(named("cp packages/${{ matrix.name }}/platforms x"), {"packages/canvas/platforms"}) self.assertEqual(jobs.each_leg("cp packages/${{ matrix.m.name }}/x/${{ matrix.arch }}", {"m.name": ["a"], "arch": ["x64", "arm64"]}), @@ -283,7 +303,8 @@ class Goals(unittest.TestCase): """The keys do what the change set out to: a TypeScript edit rebuilds nothing, a crate edit every platform that links it, a Windows script edit only Windows, a Makefile edit every make job, and a file nobody has placed everything. The check fails a job that reads what its key - leaves out.""" + leaves out. The base is HEAD with the working tree on top, untracked files too, so a local run + tests the change being made; CI's tree is clean.""" @classmethod def setUpClass(cls): @@ -370,8 +391,17 @@ def test_check_fails_a_dir_a_script_copies(self): def test_check_fails_a_value_of_the_run(self): script = "tools/scripts/build-napi.sh" - rev = self.commit(script, self.show(script) + '\necho "$GITHUB_SHA" > stamp\n') - self.assertTrue(any("GITHUB_SHA" in p for p in self.problems("canvas-windows", rev))) + for line, needle in (('echo "$GITHUB_SHA" > stamp', "GITHUB_SHA"), ("git describe --tags > stamp", "commit")): + with self.subTest(line=line): + rev = self.commit(script, self.show(script) + f"\n{line}\n") + self.assertTrue(any(needle in p for p in self.problems("canvas-windows", rev))) + + def test_a_followed_script_is_held_to_the_refusals(self): + script = "tools/scripts/build-napi.sh" + for line in ("npx nx run canvas:build", "cargo build --workspace", "python3 -m gen", '[ -n "$X" ] && . "$DIR/$NAME.sh"'): + with self.subTest(line=line): + self.assertRaises(ni.Failure, self.problems, "canvas-windows", self.commit(script, self.show(script) + f"\n{line}\n")) + self.problems("canvas-windows", self.commit(script, self.show(script) + '\n[ -f "$HOME/.cargo/env" ] && . "$HOME/.cargo/env"\n')) def test_check_holds_the_claims_about_fixtures(self): rule = "apps/demo/src/assets/file-assets/audio" @@ -402,6 +432,8 @@ def test_the_wiring(self): for name, new in (("unguarded", " - name: Build Rust libraries\n run: make android"), ("|| guard", guarded.replace("!= 'true'", "!= 'true' || always()")), ("status function", guarded.replace("!= 'true'", "!= 'true' && !success()")), + ("status function in another case", guarded.replace("!= 'true'", "!= 'true' && Always()")), + ("continue-on-error", guarded + "\n continue-on-error: true"), ("run context", guarded.replace("run: make android", "run: echo ${{ github.sha }} && make android"))): with self.subTest(name=name): self.assertRaises(ni.Failure, wiring.check_wiring, self.edit(ni.BUILD_NATIVE, guarded, new)) @@ -433,7 +465,9 @@ def test_the_wiring_of_an_artifact_built_in_parts(self): " with:\n name: canvas-ios\n"), ("last job running after a failed part", combine, combine.replace("'true'\n", "'true' && !cancelled()\n")), - ("last job not needing the parts", combine, combine.replace(", canvas-apple]", "]"))): + ("last job not needing the parts", combine, combine.replace(", canvas-apple]", "]")), + ("if: continued on the next line", combine, + combine.replace("'true'\n", "'true' &&\n always()\n"))): with self.subTest(name=name): self.assertRaises(ni.Failure, wiring.check_wiring, self.edit(ni.BUILD_NATIVE, old, new)) self.assertIn(f"{ni.BUILD_NATIVE}#canvas-apple", ni.key_inputs("canvas-ios", self.base)) @@ -442,9 +476,10 @@ def test_check_fails_a_build_file_naming_a_crate_outside_the_closure(self): rev = self.commit("packages/audio-context/src-native/android/extra.gradle", 'cargo { module = "../../../../crates/canvas-core" }\n') self.assertTrue(any("crates/canvas-core" in p for p in self.problems("audio-context-android", rev))) - def test_a_shared_job_counts_only_matrix_made_paths_against_its_legs(self): + def test_a_shared_job_reads_with_each_artifacts_own_matrix_values(self): build = " run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi ${{ matrix.module.crate }}" for line, flagged in (("cp -R packages/canvas-media/platforms/windows/x64/ x", True), + ("cp packages/canvas-media/platforms/windows/${{ matrix.arch }}/canvasmedia.node x", True), ("cp -R packages/${{ matrix.module.name }}/platforms/windows/x64/ x", False)): with self.subTest(line=line): rev = self.edit(ni.BUILD_NATIVE, build, build.replace("run: ", f"run: {line} && ")) From 80e6471adecf6e40b5c793d65598c2e5d7797ca7 Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:07:49 +0800 Subject: [PATCH 06/12] ci: read quoted cd and assignment words; require -p for every cargo build The key scan read only the first quoted part of a shell word, so after `cd "$(dirname "$0")/../../packages/canvas-svg/src-native/ios"`, as in canvas-svg-build.sh, a relative read was resolved from the wrong dir. A read of canvas_ios.h there went unseen, and canvas-svg-ios could reuse a stale xcframework. A word's quoted and bare parts are now one word, and $(dirname "$0") is the script's own dir. The check now also reads: - every value of a variable that a cd goes to; - the default in ${X:-...}; - a path after a dir named another way (format!("{}/x"), root + '/x'); - a value given to a command (X=dir cmd) and a heredoc's body; - join() segments over several lines; - get_filename_component modes other than DIRECTORY. A cargo build must name every crate with -p, without a glob and without --workspace or --all, in any dir and after --manifest-path. This holds for plugins (zigbuild, ndk), behind launchers (rustup run, xcrun, cross) and for a computed cargo. The wiring check expands a matrix job's native-cache artifact for every leg, so a leg with no ARTIFACTS entry fails Static Checks rather than its build. A local action's step may not use continue-on-error or a status function. Git global options and rev-list count as commit reads. native-inputs.py adds the root manifest's [patch] and [replace] targets to every crate closure, since cargo metadata reports a patched dependency with no path. Today they are non-members and already in the closure, so no key changes. It also runs git from the repo root, so a key computes from any dir. --- tools/scripts/native-inputs.py | 30 ++++++++-- tools/tests/check-native-inputs.py | 94 +++++++++++++++++------------- tools/tests/native_check/jobs.py | 58 +++++++++++++----- tools/tests/native_check/paths.py | 86 ++++++++++++++++++--------- tools/tests/native_check/wiring.py | 13 +++-- tools/tests/test_native_inputs.py | 83 +++++++++++++++++++++++++- 6 files changed, 264 insertions(+), 100 deletions(-) diff --git a/tools/scripts/native-inputs.py b/tools/scripts/native-inputs.py index 393a6c673..8b57f0e46 100644 --- a/tools/scripts/native-inputs.py +++ b/tools/scripts/native-inputs.py @@ -16,8 +16,9 @@ has placed rebuilds every output rather than none: * crates: those in its entry in ARTIFACTS and every workspace crate they reach through path dependencies, as `cargo metadata` reports them for the commit's manifests, with every crate dir - that is not a workspace member (the [patch] targets under crates/vendor), the root Cargo.toml, - .cargo/, rust-toolchain* and Cargo.lock. Of the other members, the dependencies each declares + that is not a workspace member and every dir the root Cargo.toml's [patch] and [replace] tables + point a dependency at (crates/vendor), the root Cargo.toml, .cargo/, rust-toolchain* and + Cargo.lock. Of the other members, the dependencies each declares and its rust-version: Cargo.lock is not committed, so cargo resolves one set of versions for the whole workspace, and a requirement in any member can move what every build links. An artifact without crates reads none of these; @@ -51,6 +52,8 @@ import tarfile import tempfile +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + BUILD_NATIVE = ".github/workflows/build-native.yml" CACHE_ACTION = ".github/actions/native-cache" NAPI_CRATES = ["crates/canvas-napi", "crates/canvas-svg-napi", "crates/audio-context-napi", @@ -186,7 +189,8 @@ class Failure(Exception): def git(*args, data=None, binary=False): - result = subprocess.run(["git", "-c", "core.quotepath=off", *args], input=data, capture_output=True) + # From the repo's root: ls-tree and archive take paths relative to the dir git runs in. + result = subprocess.run(["git", "-c", "core.quotepath=off", *args], input=data, capture_output=True, cwd=ROOT) if result.returncode != 0: raise Failure(f"git {' '.join(args[:2])}: {result.stderr.decode(errors='replace').strip()}") return result.stdout if binary else result.stdout.decode("utf-8") @@ -401,8 +405,10 @@ def rel(path): def closure(rev, start): - """The crate dirs an artifact building start reads: start, the members they reach by path, and - every crate dir that is not a member. Nothing when start is empty.""" + """The crate dirs an artifact building start reads: start, the members they reach by path, every + crate dir that is not a member, and the dirs the root manifest patches dependencies to (cargo + metadata reports a patched dependency as a registry one, with no path). Nothing when start is + empty.""" if not start: return set() deps, _, dirs, _ = crate_meta(rev) @@ -415,7 +421,19 @@ def closure(rev, start): raise Failure(f"{crate} is not a workspace member at {rev}") seen.add(crate) queue.extend(deps[crate]) - return seen | {d for d in dirs if d not in deps} + return seen | {d for d in dirs if d not in deps} | patched(rev) + + +def patched(rev): + """The dirs the root Cargo.toml's [patch.*] and [replace] tables point dependencies at.""" + found, table = set(), "" + for line in show(rev, "Cargo.toml").split("\n"): + header = re.match(r"^\s*\[+\s*([^\]]+?)\s*\]", line) + if header: + table = header.group(1) + elif re.match(r"^(patch\.|replace$)", table): + found.update(norm(p) for p in re.findall(r"\bpath\s*=\s*\"([^\"]+)\"", line)) + return found def used_actions(rev, text, where): diff --git a/tools/tests/check-native-inputs.py b/tools/tests/check-native-inputs.py index 3d377e953..bda97cd30 100644 --- a/tools/tests/check-native-inputs.py +++ b/tools/tests/check-native-inputs.py @@ -13,40 +13,44 @@ narrow, and a file no rule places is in every key. Reading the job: its steps and job-level keys, its actions' steps (with $GITHUB_ACTION_PATH as the -action's dir), the files they run and the files those mention, what `make -n` prints for the -targets it runs, and the scripts in the package dirs OWNERS gives the artifact, followed in turn. -In a job whose legs build different artifacts, matrix values are this artifact's legs' (the item of -a list of maps that names it in the native-cache `artifact:`). It fails when a file read that way -is outside the key, a crate named that way (by package name or dir) is outside the closure, or the -job cannot be read: a file run that is not tracked, a file a step runs after `cd`, a path above the -repo, a script argument (`bash build`) that is no file, `python -m`, a package runner, cargo -building crates it does not name (these four in followed shell scripts too), an unclosed quote or -heredoc, a value continued on plain lines, `make` in any form but `make [-jN] [VAR=x] ` -from the repo root, a Makefile with conditionals, includes, $(shell) or paths of the dir it runs -in, a Makefile that reads a variable it does not set (or a `?=` default in a path), which the -environment would choose, a followed script that runs make (but the third-party builds in OWN_MAKE) -or sources a computed path inside the repo, a matrix list over several lines, a local action -without action.yml, a workflow key after `jobs:`, a YAML anchor or alias, or a workflow- or -job-wide working-directory. +action's dir), the files they run and the files those mention, what `make -n` prints for the targets +it runs, and the scripts in the package dirs OWNERS gives the artifact, followed in turn. In a job +whose legs build different artifacts, matrix values are this artifact's legs' (the item of a list of +maps that names it in the native-cache `artifact:`). It fails when a file read that way is outside +the key, a crate named that way (by package name or dir) is outside the closure, or the job cannot +be read: a file run that is not tracked, a file a step runs after `cd`, a path above the repo, a +script argument (`bash build`) that is no file, `python -m`, a package runner, cargo building crates +it does not name (these four in followed shell scripts too: any cargo subcommand but those that +build nothing, a plugin's or behind a launcher too, needs -p for each crate, without a glob, and no +--workspace or --all, wherever it runs), an unclosed quote or heredoc, a value continued on plain +lines, `make` in any form but `make [-jN] [VAR=x] ` from the repo root, a Makefile with +conditionals, includes, $(shell) or paths of the dir it runs in, a Makefile that reads a variable it +does not set (or a `?=` default in a path), which the environment would choose, a followed script +that runs make (but the third-party builds in OWN_MAKE) or sources a computed path inside the repo, +a matrix list over several lines, a local action without action.yml, a workflow key after `jobs:`, a +YAML anchor or alias, or a workflow- or job-wide working-directory. Scanning the key: every text file in the key but prose (docs, notices, git's own files), the -workflows, action manifests and Makefile, and the step and job-key text the first pass reads (and -a followed script from the dir a step runs it in), are searched for paths that lead out of the -key. A path counts relative to the repo or to the file's dir, and when it goes up (`..`), from any -dir above the file; from every dir the text has `cd` to; after a variable the file sets -(`set(DIR ...)`, `DIR=...`), with each of its values; after any other variable -(`${CMAKE_CURRENT_SOURCE_DIR}`, `env!("CARGO_MANIFEST_DIR")` with `"/../x"`), from any of those -dirs, with or without the `..` after it; after a compiler flag (`-I`, `-L`, `-F`); with a glob or -another variable (a matrix value too) standing for one path segment, or for the dir it is in when -that matches nothing; given as the segments of a join() or resolve() call; in the values of a -CMake set() list or an exported shell variable; and naming a dir, for every file under it, or a -crate dir outside the closure (but in a Cargo.toml, which cargo metadata reads). In shell text, a -bare word given to a reading command (`ls apps`) is a path, and what a line only writes (the -arguments of mkdir, rm and touch, the destination of cp and the like, a redirection's target) or -prints (echo without a redirection) is not. Comments, by each kind of file's syntax, are not -paths. Crates' tests, benches and examples count only for the jobs in CARGO_TESTS, which run -`cargo test`. A text file in the key over 2 MB fails, as it cannot be scanned. This pass holds the -claims about build files, such as the C++ the Android CMake builds compile from the iOS package dir. +workflows, action manifests and Makefile, and the step and job-key text the first pass reads (and a +followed script from the dir a step runs it in), are searched for paths that lead out of the key. A +path counts relative to the repo or to the file's dir, and when it goes up (`..`), from any dir +above the file; from every dir the text has `cd` to, with each of its values; after a variable the +file sets (`set(DIR ...)`, `DIR=...`, the default in `${DIR:-...}`), with each of its values; after +any other variable or a dir named some other way (`${CMAKE_CURRENT_SOURCE_DIR}`, +`env!("CARGO_MANIFEST_DIR")` with `"/../x"`, `format!("{}/x", root)`, `root + '/x'`), from any of +those dirs, with or without the `..` after it; after a compiler flag (`-I`, `-L`, `-F`); with a glob +or another variable (a matrix value too) standing for one path segment, or for the dir it is in when +that matches nothing; given as the segments of a join() or resolve() call; in the values of a CMake +set() list or a shell variable that is exported or given to a command (`DIR=x cmd`), and in a +heredoc's body; and naming a dir, for every file under it, or a crate dir outside the closure (but +in a Cargo.toml, which cargo metadata reads). In shell text, a shell word's quoted and bare parts +are one word (`cd "$ROOT"/x`), the script's own dir (`$(dirname "$0")`) is its dir, a bare word +given to a reading command (`ls apps`) is a path, and what a line only writes (the arguments of +mkdir, rm and touch, the destination of cp and the like, a redirection's target) or prints (echo +without a redirection) is not. Comments, by each kind of file's syntax, are not paths. Crates' +tests, benches and examples count only for the jobs in CARGO_TESTS, which run `cargo test`. A text +file in the key over 2 MB fails, as it cannot be scanned. This pass holds the claims about build +files, such as the C++ the Android CMake builds compile from the iOS package dir. A path a file names but its job does not read there is listed in NOT_READ with the reason, for both passes. @@ -60,13 +64,14 @@ And the wiring: each job that uploads an artifact in build-native.yml is one of an artifact's, and each artifact's first job restores it: a native-cache step with `id: native` right after the checkout, for its own artifact and the upload's path, with `variant: ${{ toJSON(matrix) }}` in a -matrix job, every later step but the upload skipped on a hit (its `if:` is -`steps.native.outputs.hit != 'true'`, or that && more, with no ||), and one upload, under its -artifact's name. An artifact built by several jobs (the xcframeworks) has a first job that restores -it with `restore-only: 'true'`, only uploads it on a hit, and has the step's `hit` and `key` as -outputs. Its other jobs need the first and have `if: needs..outputs.hit != 'true'` (or that -&& more, with no ||), and the last of them needs every other and restores it as above, with `key: -${{ needs..outputs.key }}`, and saves it. No job of an artifact has a status function in an +matrix job, every later step but the upload skipped on a hit (its `if:` is `steps.native.outputs.hit +!= 'true'`, or that && more, with no ||), and one upload, under its artifact's name. An artifact +built by several jobs (the xcframeworks) has a first job that restores it with `restore-only: +'true'`, only uploads it on a hit, and has the step's `hit` and `key` as outputs. Its other jobs +need the first and have `if: needs..outputs.hit != 'true'` (or that && more, with no ||), and +the last of them needs every other and restores it as above, with `key: ${{ +needs..outputs.key }}`, and saves it. In a matrix job, the `artifact:` of each leg is one of +the job's entries. No job of an artifact, nor a step of its actions, has a status function in an `if:` or continue-on-error, which run on after a failure and save what is left. No local action's descriptions hold `${{ }}`, which stop the runner loading it. For the reader, a make target made of a matrix value counts once per value the strategy lists. @@ -82,10 +87,9 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the parts, however this is loaded from native_check import ni # noqa: E402 -from native_check.jobs import discover, each_leg, named_crates # noqa: E402 +from native_check.jobs import discover, each_leg, field, named_crates # noqa: E402 from native_check.paths import CARGO_TESTS, MATCHED, code, crossings, names, not_read, scan # noqa: E402 -from native_check.wiring import READS_COMMIT, RUN_VARIABLE, check_wiring, expressions, moves_cache, varying # noqa: E402 - +from native_check.wiring import READS_COMMIT, RUN_VARIABLE, STATUS, check_wiring, expressions, moves_cache, varying # noqa: E402 def check_reads(artifact, rev): @@ -108,6 +112,12 @@ def check_reads(artifact, rev): problems.append(f"{artifact}: its job reads the commit ({READS_COMMIT.search(corpus).group(0)}), which can " f"change between runs that share a key") for manifest, step in action_steps: + # As in the job: a step that runs after a failure lets the job pass and save what is left. + if STATUS.search(field(step, "if")): + problems.append(f"{artifact}: {manifest}: `if: {field(step, 'if').strip()}` holds a status function, which " + f"runs it after what it follows failed") + if field(step, "continue-on-error"): + problems.append(f"{artifact}: {manifest}: continue-on-error runs it on after a failure, and the cache saves what is left") if not moves_cache(step): for context in varying(expressions([], [step]), in_action=True): problems.append(f"{artifact}: {manifest} uses {context}, which can change between runs that share a key") diff --git a/tools/tests/native_check/jobs.py b/tools/tests/native_check/jobs.py index 18d9ea7cf..28ceb4201 100644 --- a/tools/tests/native_check/jobs.py +++ b/tools/tests/native_check/jobs.py @@ -37,6 +37,9 @@ "pacman", "port", "apk", "winget", "zypper"} PACKAGE_RUNNERS = {"npm", "npx", "yarn", "pnpm", "nx", "bun", "just"} CARGO_BUILDS = {"build", "b", "test", "t", "check", "c", "run", "r", "bench", "clippy", "doc", "d", "rustc"} +# cargo's subcommands that build no crate of the workspace; any other (a plugin too) may. +CARGO_NO_BUILD = {"install", "uninstall", "metadata", "fetch", "fmt", "version", "help", "search", "tree", "update", + "locate-project", "pkgid", "generate-lockfile", "vendor", "new", "init", "login", "logout", "owner"} WORKSPACE_PREFIX = re.compile(r"\$\{\{\s*github\.workspace\s*\}\}/|\$\{?(?:GITHUB_WORKSPACE|ROOT|REPO_ROOT|PWD)\}?/") @@ -68,6 +71,19 @@ def is_dynamic(token): return re.search(r"[$*?{}\[\]]", token) is not None +def packages(args): + """The crates cargo's -p/--package arguments name.""" + named = [] + for i, a in enumerate(args): + if a in ("-p", "--package") and i + 1 < len(args): + named.append(args[i + 1]) + elif a.startswith("--package="): + named.append(a.split("=", 1)[1]) + elif a.startswith("-p") and not a.startswith("--") and len(a) > 2: + named.append(a[2:]) + return named + + def looks_like_file(token): return "/" in token or re.search(r"\." + SCRIPT_EXT + "$", token) is not None @@ -339,13 +355,19 @@ def walk(script, wd, where, files, guesses, makes, after_cd, followed=False): raise ni.Failure(f"{where}: cannot follow the make in `{command}`; run `make ` itself") if base in PACKAGE_RUNNERS: raise ni.Failure(f"{where}: `{command}` runs what a package manifest says; run the script itself") - # --workspace builds crates no one names wherever it runs; without -p, cargo builds the - # crate of the dir it runs in, which only a cd or working-directory can name. - if base == "cargo" and first in CARGO_BUILDS and ({"--workspace", "--all"} & set(args) or ( - not (wd or after_cd) and not any( - a in ("-p", "--package", "--manifest-path") or a.startswith(("--package=", "--manifest-path=")) - or (a.startswith("-p") and not a.startswith("--")) for a in args))): - raise ni.Failure(f"{where}: `{command}` builds crates it does not name; name each with -p") + # Without -p, cargo builds the crate of the dir it runs in, or every member from a dir that + # is no crate's; --workspace builds every member wherever it runs. So each build names its + # crates, also behind a launcher (rustup run, xcrun, cross) or a plugin (zigbuild, ndk). + at = next((i for i, t in enumerate(tokens) if posixpath.basename(t) in ("cargo", "cross")), None) + if at is None and is_dynamic(name) and first in CARGO_BUILDS: + at = 0 + if at is not None and base not in NAMES_ONLY: + cargo = tokens[at + 1:] + words = {a for a in cargo if not a.startswith(("-", "+"))} + crates = packages(cargo) + if words and not words & CARGO_NO_BUILD and ( + {"--workspace", "--all"} & set(cargo) or not crates or any(re.search(r"[*?\[]", c) for c in crates)): + raise ni.Failure(f"{where}: `{command}` builds crates it does not name; name each with -p") if name in ("cd", "pushd"): after_cd = True elif followed: @@ -487,7 +509,7 @@ def reach(p, how, wd=""): wd_of[p] = wd todo.append(p) - def take(step, step_where, scan, values=None, job=None): + def take(step, step_where, scan, values=None): wd, files, step_guesses, make = commands(step, step_where, values) text = "\n".join(step) corpus.append(text) @@ -500,7 +522,7 @@ def take(step, step_where, scan, values=None, job=None): executed.add(p) reach(p, step_where, wd) if scan: - texts_read.append(Read(step_where, job, text, wd, values or {})) + texts_read.append(Read(step_where, text, wd, values or {})) for p in mentions(text, [wd], tree): reach(p, step_where, wd) guesses.extend(step_guesses) @@ -518,13 +540,13 @@ def take(step, step_where, scan, values=None, job=None): # A matrix names every leg's values, each leg reads its own, and its key has them (variant). # In a job whose legs build different artifacts, the values are this artifact's legs'. matrix = sections(outside, 4, {"strategy"}) - cache = next((s for s in steps if re.search(r"uses:\s*\./\.github/actions/native-cache\b", "\n".join(s))), []) + cache = native_cache(steps) or [] values = matrix_values(matrix, artifact, field(cache, "artifact")) - texts_read.append(Read(f"{where} job keys", (path, job_id), "\n".join(l for l in outside if l not in matrix), "", values)) + texts_read.append(Read(f"{where} job keys", "\n".join(l for l in outside if l not in matrix), "", values)) for p in mentions("\n".join(outside), [], tree): reach(p, f"{where} job keys") for step in steps: - take(step, where, True, values, (path, job_id)) + take(step, where, True, values) for p in sorted(tree): if own(p) and p.endswith((".sh", ".bash")): reach(p, f"a script in {artifact}'s dirs") @@ -591,13 +613,17 @@ def take(step, step_where, scan, values=None, job=None): reach(found, p, wd_of.get(p, "")) # Run from another dir, its relative paths are read from there too. if wd_of.get(p, "") not in ("", here): - texts_read.append(Read(p, None, text, wd_of[p], {})) + texts_read.append(Read(p, text, wd_of[p], {})) return reads, "\n".join(corpus), action_steps, texts_read -# Text the job pass read: where it is, its job (path, id) if it is a job's, its working-directory, -# and the values its job's matrix lists. -Read = collections.namedtuple("Read", "where job text wd values") +# Text the job pass read: where it is, its working-directory, and the values its job's matrix lists. +Read = collections.namedtuple("Read", "where text wd values") + + +def native_cache(steps): + """A job's native-cache step, or None.""" + return next((s for s in steps if re.search(r"uses:\s*\./\.github/actions/native-cache\b", "\n".join(s))), None) def sections(lines, column, keys): diff --git a/tools/tests/native_check/paths.py b/tools/tests/native_check/paths.py index 67a35d6a9..0ee93f4b4 100644 --- a/tools/tests/native_check/paths.py +++ b/tools/tests/native_check/paths.py @@ -7,6 +7,7 @@ import re from . import ni +from .jobs import SCRIPT_DIR_REF # The artifacts whose job runs `cargo test` on its crates, which builds their tests and examples. @@ -50,21 +51,29 @@ def whole(pattern): # `#` after a space or at a line's start, but not Ruby's `#{`. HASH_COMMENT = re.compile(STRING + r"|((?:^|(?<=\s))#(?!\{)[^\n]*)", re.M) XML_COMMENT = re.compile(r"()", re.S) +# A shell word: quoted and bare parts with nothing between them (`"$ROOT"/packages/x`). +WORD = r"(?:\"[^\"]*\"|'[^']*'|[^\s;&|()'\"])+" # Where a file sets a variable to a path: a shell assignment anywhere on a line, CMake's set(), and -# get_filename_component() with DIRECTORY, whose value is the dir above the path it is given. -SHELL_SET = re.compile(r"(?:^|[\s;&|()])(export\s+|(?:local|readonly|declare)\s+(?=\w))?([A-Za-z_]\w*)=" - r"(\"[^\"]*\"|'[^']*'|[^\s;&|()]*)") +# get_filename_component(), whose DIRECTORY or PATH is the dir above the path it is given. +SHELL_SET = re.compile(r"(?:^|[\s;&|()])(export\s+|(?:local|readonly|declare)\s+(?=\w))?([A-Za-z_]\w*)=(" + WORD + ")?") CMAKE_SET = re.compile(r"^\s*(set|get_filename_component)\(\s*([A-Za-z_]\w*)\s+\"?([^\s\")]+)\"?([^)]*)", re.I) -# A variable: ${{ }}, then the named forms (`${X}`, `$(X)`, `$X`), then any other (Ruby's #{x} too). +# A variable: ${{ }}, then the named forms (`${X}`, `$(X)`, `$X`, `${X:-default}`), then any other +# (Ruby's #{x} too). VARIABLE = re.compile(r"\$\{\{[^}]*\}\}|\$\{([A-Za-z_]\w*)\}|\$\(([A-Za-z_]\w*)\)|\$([A-Za-z_]\w*)" + r"|\$\{([A-Za-z_]\w*):?[-=]([^}]*)\}" r"|\$\{[^}]*\}|\$\([^)]*\)|#\{[^}]*\}|@[A-Za-z_]\w*@|%[A-Za-z_]\w*%") -# A shell's `cd`/`pushd` and where to. -CD = re.compile(r"(?:^|[\s;&|(])(?:cd|pushd)\s+(\"[^\"]*\"|'[^']*'|[^\s;&|)]+)") +# What follows an assignment that a command is given: the command's word on the same line. +PREFIX = re.compile(r"[ \t]+(?![A-Za-z_]\w*=)[^\s;&|()]") +# A shell's `cd`/`pushd` and where to, and a heredoc's delimiter. +CD = re.compile(r"(?:^|[\s;&|(])(?:cd|pushd)\s+(" + WORD + ")") +HEREDOC = re.compile(r"(?\[\]|&:!]*/[^\s'\"`=;,(){}<>\[\]|&:!]*") # A path given as its segments: path.join(root, 'apps', 'demo'), os.path.join(ROOT, "x"). JOIN = re.compile(r"\b(?:join|resolve)\(([^()]*)\)") WILD = "\x01" WILDS = r"[*?" + WILD + "]" +# A value that is a path as written, not a command's output. +PLAIN = re.compile(r"^[\w./@+" + WILD + "-]*$") @functools.lru_cache(maxsize=None) @@ -130,8 +139,10 @@ def expand(text, values): if m is None: return [text] rests = expand(text[m.end():], values) - name = m.group(1) or m.group(2) or m.group(3) + name = m.group(1) or m.group(2) or m.group(3) or m.group(4) options = (values.get(name) if name else None) or [WILD] + if m.group(5): + options = list(dict.fromkeys(options + expand(unquote(m.group(5)), values))) if len(options) * len(rests) > 64: options = [WILD] return [text[:m.start()] + option + rest for option in options for rest in rests] @@ -143,8 +154,10 @@ def resolve_token(token, here, entries, matched): does not name (an unknown variable, or `"/../x"` after env!("CARGO_MANIFEST_DIR") or the like), may start from any dir above the file, and after an unknown dir, the `..` may lead anywhere. A computed name that matches nothing names its dir.""" - token = re.sub(r"^-(?:I|L|F|isystem|iquote|idirafter|include)(?=\S)", "", token) - if token.startswith("/.."): + token = re.sub(r"^(?:\./)+", "", re.sub(r"^-(?:I|L|F|isystem|iquote|idirafter|include)(?=\S)", "", token)) + # `/x` is a path after a dir the text names some other way (format!("{}/x"), root + '/x') or + # outside the repo, where it matches no tracked entry. + if token.startswith("/") and not token.startswith("//"): token = WILD + token unknown = token.startswith(WILD + "/") token = re.sub(r"^(" + WILD + r"/)+", "", token).rstrip(".") @@ -237,44 +250,61 @@ def shell_reads(line): def path_tokens(text, shell=False): """The paths the text names: its tokens with a `/` (and in shell text, the bare words a reading command is given, without what a line only writes or prints), with the variables it sets - expanded, the values of the ones it exports and of CMake's set() lists, and each relative path - also from every dir the text has `cd` to. The text is code: its comments already gone.""" + expanded, the values it gives them and CMake's set() lists, join()'s segments, and each relative + path also from every dir the text has `cd` to. In shell text, the script's own dir is `.`. The + text is code: its comments already gone.""" values, found, dirs = {}, set(), [] def define(name, value): # A value that is not a plain path (a command's output, say) is unknown. values.setdefault(name, []) - values[name] += [v if re.match(r"^[\w./@+" + WILD + "-]*$", v) else WILD - for v in expand(value.strip("'\""), values) if v not in values[name]] - - lines = re.sub(r"\\\n", " ", text).split("\n") if shell else text.split("\n") - for line in lines: + values[name] += [v if PLAIN.match(v) else WILD for v in expand(unquote(value), values) if v not in values[name]] + + if shell: + text = SCRIPT_DIR_REF.sub(".", re.sub(r"\\\n", " ", text)) + heredoc = None + for line in text.split("\n"): + if heredoc is not None: + # A heredoc's body is text a command is given (a config file, say), not commands. + heredoc = None if line.strip() == heredoc else heredoc + found.update(t for expanded in expand(line, values) for t in TOKEN.findall(expanded)) + continue + if shell and HEREDOC.search(line): + heredoc = HEREDOC.search(line).group(1) cmake = CMAKE_SET.match(line) if cmake: - define(cmake.group(2), cmake.group(3) + ("/.." if cmake.group(1).lower() != "set" else "")) + mode = (cmake.group(4).split() or [""])[0].upper() + define(cmake.group(2), cmake.group(3) + ("/.." if mode in ("DIRECTORY", "PATH") else "")) # A list's values are what is built from (sources); one value names a dir its uses extend. line = " ".join(cmake.group(3, 4)) if cmake.group(1).lower() == "set" and cmake.group(4).strip() else "" for m in SHELL_SET.finditer(line): - define(m.group(2), m.group(3)) - exported = " ".join(m.group(3) for m in SHELL_SET.finditer(line) if m.group(1)) + define(m.group(2), m.group(3) or "") for cd in CD.finditer(line): - if cd.group(1).strip("'\"") == "-": + target, before = unquote(cd.group(1)), dirs[-1] if dirs else None + if target == "-": continue - to = expand(cd.group(1).strip("'\""), values)[0] - to = to if re.match(r"^[\w./@+" + WILD + "-]*$", to) else WILD - # As given and from the dir before it, since a popd or subshell may have left that one. - dirs += [to] + ([posixpath.join(dirs[-1], to)] if dirs and not to.startswith(("/", WILD)) else []) - rest = SHELL_SET.sub(" ", line) + " " + exported + for to in expand(target, values): + to = to if PLAIN.match(to) else WILD + # As given and from the dir before it, since a popd or subshell may have left that one. + dirs += [to] + ([posixpath.join(before, to)] if before and not to.startswith(("/", WILD)) else []) + # A value is read where it is exported or given to the command after it (`X=dir cmd`); one + # only set may be a dir the script goes on to name parts of. + rest = SHELL_SET.sub(lambda m: " " + (unquote(m.group(3) or "") if m.group(1) or PREFIX.match(line, m.end()) else ""), line) for expanded in expand(shell_reads(rest) if shell else rest, values): tokens = TOKEN.findall(expanded) - for m in JOIN.finditer(expanded): - args = [a.strip() for a in m.group(1).split(",")] - tokens.append("/".join(a[1:-1] if len(a) > 1 and a[0] == a[-1] and a[0] in "'\"" else WILD for a in args)) found.update(tokens) found.update(posixpath.join(d, t) for d in dirs for t in tokens if not t.startswith(("/", WILD))) + for m in JOIN.finditer(text): + args = [a.strip() for a in m.group(1).split(",")] + found.update(expand("/".join(a[1:-1] if len(a) > 1 and a[0] == a[-1] and a[0] in "'\"" else WILD for a in args), values)) return tuple(sorted(found)) +def unquote(word): + """A shell word without its quotes.""" + return re.sub(r"\"([^\"]*)\"|'([^']*)'", lambda m: m.group(1) if m.group(1) is not None else m.group(2), word) + + @functools.lru_cache(maxsize=None) def named_paths(rev, p): text = code(texts(rev)[p], p) diff --git a/tools/tests/native_check/wiring.py b/tools/tests/native_check/wiring.py index 60e8a0d82..a20f6e4ad 100644 --- a/tools/tests/native_check/wiring.py +++ b/tools/tests/native_check/wiring.py @@ -3,7 +3,7 @@ import re from . import ni -from .jobs import field, sections +from .jobs import each_leg, field, matrix_values, native_cache, sections GUARD = "steps.native.outputs.hit != 'true'" @@ -17,7 +17,8 @@ r"EVENT_PATH|RUN_ID|RUN_NUMBER|RUN_ATTEMPT|ACTOR|ACTOR_ID|TRIGGERING_ACTOR|WORKFLOW|" r"WORKFLOW_REF|WORKFLOW_SHA|RETENTION_DAYS)\b") # Git commands whose output is the commit, which differs between commits that share a key. -READS_COMMIT = re.compile(r"\bgit\s+(?:describe|log|show|rev-parse\s+(?:--\S+\s+)*(?:HEAD|@)\b)") +READS_COMMIT = re.compile(r"\bgit\s+(?:(?:-[Cc]\s+\S+|--\S+)\s+)*" + r"(?:describe|log|show|rev-list|rev-parse\s+(?:--\S+\s+)*(?:HEAD|@)\b)") def moves_cache(step): @@ -80,7 +81,7 @@ def check_wiring(rev): if (path, job_id) in artifacts_of: raise continue - cache = next((s for s in steps if re.search(r"uses:\s*\./\.github/actions/native-cache\b", "\n".join(s))), None) + cache = native_cache(steps) uploads = [s for s in steps if re.match(r"^actions/upload-artifact@", field(s, "uses"))] if (path, job_id) not in artifacts_of: if path == ni.BUILD_NATIVE and (uploads or cache): @@ -105,8 +106,10 @@ def check_wiring(rev): if field(cache, "id") != "native": problems.append(f"{where}: the native-cache step needs `id: native`") artifact = field(cache, "artifact") - if "${{" not in artifact and artifact not in artifacts_of[path, job_id]: - problems.append(f"{where}: native-cache artifact '{artifact}' is not one of this job's entries") + # In a matrix job, each leg's: an entry no leg names is never built, and a leg no entry + # lists has no key. + for leg in sorted(set(each_leg(artifact, matrix_values(outside)).split()) - set(artifacts_of[path, job_id])): + problems.append(f"{where}: native-cache artifact '{leg}' is not one of this job's entries") if any(not re.match(r"^actions/checkout@", field(s, "uses")) for s in steps[:steps.index(cache)]): problems.append(f"{where}: only the checkout may come before the native-cache step") if any(re.match(r"^\s+matrix:", l) for l in outside) and re.sub(r"\s", "", field(cache, "variant")) != "${{toJSON(matrix)}}": diff --git a/tools/tests/test_native_inputs.py b/tools/tests/test_native_inputs.py index f7f52a6b6..54dd30048 100644 --- a/tools/tests/test_native_inputs.py +++ b/tools/tests/test_native_inputs.py @@ -105,6 +105,19 @@ def test_refusals(self): self.assertRaises(ni.Failure, ran, *lines) self.assertEqual(ran("run: cargo test -p canvas-c --features 2d")[0], set()) + def test_cargo_names_every_crate_it_builds(self): + for lines in (["working-directory: crates/canvas-c", "run: cargo build"], ["run: cargo build --manifest-path Cargo.toml"], + ["run: cargo zigbuild --workspace -p a"], ["run: cargo ndk -t arm64-v8a build"], + ["run: cargo -Z unstable-options build"], ["run: rustup run nightly cargo build"], + ["run: xcrun cargo build"], ["run: cross build"], ['run: "$REAL_CARGO" build'], + ["run: cargo build -p 'canvas-*'"]): + with self.subTest(lines=lines): + self.assertRaises(ni.Failure, ran, *lines) + for line in ("run: cargo +nightly build -Z build-std=std --target x -p canvas-ios", "run: cargo build -p $CRATE", + "run: cargo install cbindgen@0.29.0 --locked", "run: cargo --version"): + with self.subTest(line=line): + ran(line) + def test_make(self): self.assertEqual(ran("run: make android")[2], (["android"], [])) self.assertEqual(ran("run: make -j 4 ios tvos")[2], (["ios", "tvos"], [])) @@ -263,6 +276,33 @@ def test_shell_bare_names_exports_and_lists(self): self.assertEqual(named("OTHER_CFLAGS = -I$(SRCROOT)/../../platforms/ios/src/cpp", "packages/canvas/src-native/android"), {"packages/canvas/platforms/ios/src/cpp"}) + def test_quoted_words_and_the_scripts_own_dir(self): + caches = "packages/canvas/platforms/ios/src/cpp/Caches.cpp" + self.assertIn(caches, named('cd "$(dirname "$0")/../packages/canvas/src-native/android"\n' + 'cp ../../platforms/ios/src/cpp/Caches.cpp x', "tools", shell=True)) + self.assertIn(caches, named('cd "$ROOT"/packages/canvas/src-native/android\ncat ../../platforms/ios/src/cpp/Caches.cpp', shell=True)) + self.assertIn("tools/assets", named('X="$ROOT"/tools/assets; cp -R "$X" out', shell=True)) + self.assertIn("tools/assets/icons/a.png", named('case $X in a) D=packages/canvas ;; b) D=tools ;; esac\n' + 'cd "$D"\ncat assets/icons/a.png', shell=True)) + + def test_a_default_a_dir_named_some_other_way_and_segments_over_lines(self): + self.assertIn("tools/assets/icons/a.png", named('F="${F:-$ROOT/tools/assets/icons/a.png}"\ngrep x "$F"', shell=True)) + self.assertEqual(named('let p = format!("{}/tools/assets/icons/a.png", root);'), {"tools/assets/icons/a.png"}) + self.assertEqual(named("const a = root + '/apps/demo/audio';"), {"apps/demo/audio"}) + self.assertEqual(named("const a = path.join(\n root,\n 'apps', 'demo', 'audio');"), {"apps/demo/audio"}) + + def test_a_value_set_is_read_where_a_command_is_given_it(self): + self.assertEqual(named("cat > cfg < stamp', "GITHUB_SHA"), ("git describe --tags > stamp", "commit")): @@ -446,6 +521,8 @@ def test_the_wiring(self): "canvas-release.aar\n if-no-files-found: error\n")) self.assertRaises(ni.Failure, wiring.check_wiring, self.edit(ni.BUILD_NATIVE, " variant: ${{ toJSON(matrix) }}\n", "")) + leg = " - name: canvas-gamepad\n crate: canvas-gamepad-napi\n file: canvasgamepad.node\n" + self.assertRaises(ni.Failure, wiring.check_wiring, self.edit(ni.BUILD_NATIVE, leg, leg + leg.replace("canvas-gamepad\n", "canvas-foo\n"))) # GitHub evaluates expressions in an action's input descriptions and fails to load it. self.assertRaises(ni.Failure, wiring.check_wiring, self.edit( f"{ni.CACHE_ACTION}/action.yml", " description: The job's entry", " description: ${{ inputs.x }} The job's entry")) From 6fb03913ca2cc7fc9c83d023061a212eef48910c Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:09:36 +0800 Subject: [PATCH 07/12] ci: warn when an xcframework's last job hits what its first job missed The xcframework's first job restores on Linux what its last job saved on macOS. If those runners ever disagree on the cache version, the first job misses every time and the four macOS part jobs build for nothing, silently. The native-cache action now prints a warning when the last job (given a key) restores an entry. A run by hand with `fresh` saves nothing, so it now has a concurrency group of its own. It can no longer replace a master push that is waiting to save the caches pull requests read. The input's description says it still publishes the prerelease, as any dispatch does. --- .github/actions/native-cache/action.yml | 10 ++++++++++ .github/workflows/pull-request.yml | 7 ++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.github/actions/native-cache/action.yml b/.github/actions/native-cache/action.yml index e7b17bfae..df51576c6 100644 --- a/.github/actions/native-cache/action.yml +++ b/.github/actions/native-cache/action.yml @@ -84,3 +84,13 @@ runs: with: path: ${{ inputs.path }} key: ${{ steps.key.outputs.key }} + + # The last job of an output built by several jobs runs only after its first job missed. A hit + # here means the parts were built for nothing: another run saved the entry meanwhile, or, when + # it repeats, the first job's runner cannot restore what this one saves. + - name: Note an entry the first job missed + if: inputs.key != '' && steps.cache.outputs.cache-hit == 'true' + shell: bash + env: + KEY: ${{ inputs.key }} + run: echo "::warning title=native-cache::restored $KEY, which the first job of this output missed" diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 0b520b9da..324e0dda5 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -19,7 +19,7 @@ on: workflow_dispatch: inputs: fresh: - description: Build every native output instead of restoring it (to check a cached output; it saves nothing) + description: Build every native output instead of restoring it, to check a cached one. Saves no cache entry; publishes the prerelease as any dispatch does type: boolean default: false @@ -28,9 +28,10 @@ env: NATIVE_CACHE_FRESH: ${{ inputs.fresh }} # A pull request push cancels the run it supersedes. On master a running build finishes (it -# saves the caches pull requests read) and only the newest waiting push runs after it. +# saves the caches pull requests read) and only the newest waiting push runs after it. A `fresh` +# run, which saves nothing, waits in a group of its own, so it never replaces a waiting push. concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ inputs.fresh && '-fresh' || '' }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: From 80dbbaa8af2426b1ae4c8f0b20237ff33058d8cf Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:25:25 +0800 Subject: [PATCH 08/12] ci: read commands in quoted substitutions; narrow the cargo and git rules - The check reads the commands in a "$(...)" or backtick substitution in double quotes, so a cargo build, a package runner or a read there is held to the same rules. A plain assignment's substitution (X="$(cat f)") counts as a read again; round 13 had dropped it. - A cargo command is found where it runs (also cargo-ndk, "$CARGO" ndk, rustup run and xcrun), and only its subcommand decides whether it builds. `cargo build --features new` needs -p; `cargo clean` and `[ "$X" = cross ]` pass. - git commands that read a commit or a ref are refused: ls-tree, cat-file, branch and the like, and a revision given to rev-parse or diff (`git rev-parse @` too). - hashFiles() is exempt only in cache steps. A large fixture in a crate's tests no longer fails the size rule, and a long line no longer recurses or stalls the scan. - build-napi.sh's own module dirs are in NOT_READ. - A `fresh` run shares master's concurrency group again, so prerelease publishes stay in order. - Comments and docstrings now say that each output (not each job) is restored, that an xcframework saves only when all five of its macOS jobs run in one run, and how to add an output. --- .github/actions/native-cache/action.yml | 2 +- .github/workflows/build-native.yml | 18 ++-- .github/workflows/pull-request.yml | 14 +-- tools/scripts/native-inputs.py | 18 +++- tools/tests/check-native-inputs.py | 67 +++++++------- tools/tests/native_check/jobs.py | 117 +++++++++++++++++++++--- tools/tests/native_check/paths.py | 66 ++++++++----- tools/tests/native_check/wiring.py | 36 ++++++-- tools/tests/test_native_inputs.py | 57 +++++++++++- 9 files changed, 293 insertions(+), 102 deletions(-) diff --git a/.github/actions/native-cache/action.yml b/.github/actions/native-cache/action.yml index df51576c6..e0e7833cb 100644 --- a/.github/actions/native-cache/action.yml +++ b/.github/actions/native-cache/action.yml @@ -20,7 +20,7 @@ inputs: description: The job's entry in tools/scripts/native-inputs.py required: true path: - description: The finished output, the same path the job uploads + description: The finished output, the path the job uploads (or, for a job that uploads nothing, a file it writes when it passes) required: true variant: description: In a matrix job, the matrix as JSON (toJSON of matrix), so every leg gets its own key diff --git a/.github/workflows/build-native.yml b/.github/workflows/build-native.yml index cf30bdea5..782509b86 100644 --- a/.github/workflows/build-native.yml +++ b/.github/workflows/build-native.yml @@ -42,14 +42,16 @@ # run the Node-API test suites on the shipped modules (on WARP: runners have no GPU; # audio renders offline and on the 'none' sink: they have no audio device either). # -# Every job first restores its finished output from .github/actions/native-cache, keyed on what it -# is built from (tools/scripts/native-inputs.py says what that covers). On a hit it skips its build -# and uploads the restored output, so a change rebuilds only the jobs that depend on it: a crate -# change rebuilds every platform that links the crate, a Windows script change only the Windows -# jobs, and a TypeScript change nothing. An output built by several jobs (the Apple xcframeworks) is -# restored by a job of its own, which on a hit uploads it and skips the jobs that build it. A job -# that builds Skia also keeps Skia's built libraries per target in .github/actions/skia-cache, saved -# only by pushes to master. +# Every output is first restored from .github/actions/native-cache, keyed on what it is built from +# (tools/scripts/native-inputs.py says what that covers). On a hit its job skips the build and +# uploads the restored output, so a change rebuilds only the jobs that depend on it: a crate change +# rebuilds every platform that links the crate, a Windows script change only the Windows jobs, and +# a TypeScript change nothing. An output built by several jobs (the Apple xcframeworks) is restored +# by a job of its own on Linux, which on a hit uploads it and skips the jobs that build it: the four +# per-platform jobs and the one that joins their slices. Only that last job saves it, so an +# xcframework is reused only once all five of its macOS jobs have run in one run. A job that builds +# Skia also keeps Skia's built libraries per target in .github/actions/skia-cache, saved only by +# pushes to master. name: Build Native permissions: diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 324e0dda5..8ce57f5e8 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -2,10 +2,10 @@ # # All native artifacts (Android AARs + iOS/visionOS/tvOS xcframeworks for # canvas, canvas-svg and audio-context; the Windows and Linux x64/arm64 -# Node-API modules) are built by the reusable build-native.yml workflow. On +# Node-API modules) are built by the reusable build-native.yml workflow, or +# restored from its cache when nothing they are built from has changed. On # pushes to master (and manual dispatch) the npm job then packages everything -# with those freshly built artifacts and publishes a `pr`-tagged prerelease of -# each package. +# with those artifacts and publishes a `pr`-tagged prerelease of each package. name: Canvas Native permissions: @@ -19,7 +19,7 @@ on: workflow_dispatch: inputs: fresh: - description: Build every native output instead of restoring it, to check a cached one. Saves no cache entry; publishes the prerelease as any dispatch does + description: Build every native output instead of restoring it, to check a cached one. Saves no native-cache entry; publishes the prerelease as any dispatch does type: boolean default: false @@ -28,10 +28,10 @@ env: NATIVE_CACHE_FRESH: ${{ inputs.fresh }} # A pull request push cancels the run it supersedes. On master a running build finishes (it -# saves the caches pull requests read) and only the newest waiting push runs after it. A `fresh` -# run, which saves nothing, waits in a group of its own, so it never replaces a waiting push. +# saves the caches pull requests read) and only the newest waiting run starts after it, so runs +# that publish the prerelease, a `fresh` one too, publish in order. concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ inputs.fresh && '-fresh' || '' }} + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: diff --git a/tools/scripts/native-inputs.py b/tools/scripts/native-inputs.py index 8b57f0e46..abec4c2cd 100644 --- a/tools/scripts/native-inputs.py +++ b/tools/scripts/native-inputs.py @@ -22,10 +22,10 @@ and its rust-version: Cargo.lock is not committed, so cargo resolves one set of versions for the whole workspace, and a requirement in any member can move what every build links. An artifact without crates reads none of these; - * workflows: the blocks of its jobs (one, but for the xcframeworks, which also have a lookup job - and the jobs that build their parts) and their workflows' settings above `jobs:` (comment lines - dropped, `run: |` text kept as written), so editing one job rebuilds only what it builds; no - workflow file; + * workflows: the blocks of its jobs (build-native.yml's job of the artifact's name, or those its + ARTIFACTS entry lists: the xcframeworks' lookup job and part jobs, for instance) and their + workflows' settings above `jobs:` (comment lines dropped, `run: |` text kept as written), so + editing one job rebuilds only what it builds; no workflow file; * actions: the dirs of the local actions its jobs use (`uses: ./dir`; naming one any other way is refused), those they use, and the native-cache action; no other action; * every other file whose last matching rule in OWNERS names the artifact, or that no rule matches. @@ -33,6 +33,14 @@ OWNERS and ARTIFACTS are claims about what each job reads. tools/tests/check-native-inputs.py, which Static Checks runs, holds them to what the jobs are seen to read and checks how the jobs are wired. +To add a native output, wire its job to .github/actions/native-cache as the check's docstring says, +give it an entry in ARTIFACTS (its crates, and its jobs unless it is build-native.yml's job of its +name), its package dirs in PACKAGE_DIRS, the tools/scripts it runs in SCRIPTS, and add it to the +platform tuples below that hold it. A new crate needs no entry: the closure finds it. A new file +outside the crates is in every key until an OWNERS rule places it. Then run the check: when it +reports a path a file names but its job does not read there (one a script writes, say), add that +to NOT_READ in tools/tests/native_check/paths.py with the reason. + Crates.io versions float within the declared ranges, and toolchains float within their pins. Neither is part of the key. The cache action adds the week to the key so nothing reused is more than a week old, and the release (npm_release.yml) builds with `fresh: true`. @@ -432,7 +440,7 @@ def patched(rev): if header: table = header.group(1) elif re.match(r"^(patch\.|replace$)", table): - found.update(norm(p) for p in re.findall(r"\bpath\s*=\s*\"([^\"]+)\"", line)) + found.update(norm(p) for _, p in re.findall(r"\bpath\s*=\s*([\"'])(.+?)\1", line)) return found diff --git a/tools/tests/check-native-inputs.py b/tools/tests/check-native-inputs.py index bda97cd30..b920c13f1 100644 --- a/tools/tests/check-native-inputs.py +++ b/tools/tests/check-native-inputs.py @@ -14,21 +14,23 @@ Reading the job: its steps and job-level keys, its actions' steps (with $GITHUB_ACTION_PATH as the action's dir), the files they run and the files those mention, what `make -n` prints for the targets -it runs, and the scripts in the package dirs OWNERS gives the artifact, followed in turn. In a job -whose legs build different artifacts, matrix values are this artifact's legs' (the item of a list of -maps that names it in the native-cache `artifact:`). It fails when a file read that way is outside -the key, a crate named that way (by package name or dir) is outside the closure, or the job cannot -be read: a file run that is not tracked, a file a step runs after `cd`, a path above the repo, a -script argument (`bash build`) that is no file, `python -m`, a package runner, cargo building crates -it does not name (these four in followed shell scripts too: any cargo subcommand but those that -build nothing, a plugin's or behind a launcher too, needs -p for each crate, without a glob, and no ---workspace or --all, wherever it runs), an unclosed quote or heredoc, a value continued on plain -lines, `make` in any form but `make [-jN] [VAR=x] ` from the repo root, a Makefile with -conditionals, includes, $(shell) or paths of the dir it runs in, a Makefile that reads a variable it -does not set (or a `?=` default in a path), which the environment would choose, a followed script -that runs make (but the third-party builds in OWN_MAKE) or sources a computed path inside the repo, -a matrix list over several lines, a local action without action.yml, a workflow key after `jobs:`, a -YAML anchor or alias, or a workflow- or job-wide working-directory. +it runs, and the scripts in the package dirs OWNERS gives the artifact, followed in turn; the +commands in a `$(...)` or backtick substitution count, in double quotes too. In a job whose legs +build different artifacts, matrix values are this artifact's legs' (the item of a list of maps that +names it in the native-cache `artifact:`). It fails when a file read that way is outside the key, a +crate named that way (by package name or dir) is outside the closure, or the job cannot be read: a +file run that is not tracked, a file a step runs after `cd`, a path above the repo, a script +argument (`bash build`) that is no file, `python -m`, a package runner, cargo building crates it +does not name (these four in followed shell scripts too: any cargo subcommand but those that build +nothing, a plugin's (`cargo ndk`, `cargo-ndk`), one behind rustup run or xcrun, or one run through a +variable (`"$CARGO" build`) too, needs -p for each crate, without a glob, and no --workspace or +--all, wherever it runs), an unclosed quote, substitution or heredoc, a value or list continued on +plain lines, `make` in any form but `make [-jN] [VAR=x] ` from the repo root, a Makefile +with conditionals, includes, $(shell) or paths of the dir it runs in, a Makefile that reads a +variable it does not set (or a `?=` default in a path), which the environment would choose, a +followed script that runs make (but the third-party builds in OWN_MAKE) or sources a computed path +inside the repo, a matrix list over several lines, a local action without action.yml, a workflow key +after `jobs:`, a YAML anchor or alias, or a workflow- or job-wide working-directory. Scanning the key: every text file in the key but prose (docs, notices, git's own files), the workflows, action manifests and Makefile, and the step and job-key text the first pass reads (and a @@ -41,16 +43,17 @@ those dirs, with or without the `..` after it; after a compiler flag (`-I`, `-L`, `-F`); with a glob or another variable (a matrix value too) standing for one path segment, or for the dir it is in when that matches nothing; given as the segments of a join() or resolve() call; in the values of a CMake -set() list or a shell variable that is exported or given to a command (`DIR=x cmd`), and in a -heredoc's body; and naming a dir, for every file under it, or a crate dir outside the closure (but -in a Cargo.toml, which cargo metadata reads). In shell text, a shell word's quoted and bare parts -are one word (`cd "$ROOT"/x`), the script's own dir (`$(dirname "$0")`) is its dir, a bare word -given to a reading command (`ls apps`) is a path, and what a line only writes (the arguments of -mkdir, rm and touch, the destination of cp and the like, a redirection's target) or prints (echo -without a redirection) is not. Comments, by each kind of file's syntax, are not paths. Crates' -tests, benches and examples count only for the jobs in CARGO_TESTS, which run `cargo test`. A text -file in the key over 2 MB fails, as it cannot be scanned. This pass holds the claims about build -files, such as the C++ the Android CMake builds compile from the iOS package dir. +set() list or a shell variable that is exported or given to a command (`DIR=x cmd`), in the commands +a shell variable's value runs (`X="$(cat f)"`), and in a heredoc's body; and naming a dir, for every +file under it, or a crate dir outside the closure (but in a Cargo.toml, which cargo metadata reads). +In shell text, a shell word's quoted and bare parts are one word (`cd "$ROOT"/x`), the script's own +dir (`$(dirname "$0")`) is its dir, a bare word given to a reading command (`ls apps`) is a path, +and what a line only writes (the arguments of mkdir, rm and touch, the destination of cp and the +like, a redirection's target) or prints (echo without a redirection) is not. Comments, by each kind +of file's syntax, are not paths. Crates' tests, benches and examples count only for the jobs in +CARGO_TESTS, which run `cargo test`. A text file in the key over 2 MB that this pass would scan +fails, as it cannot be scanned. This pass holds the claims about build files, such as the C++ the +Android CMake builds compile from the iOS package dir. A path a file names but its job does not read there is listed in NOT_READ with the reason, for both passes. @@ -59,7 +62,9 @@ steps, env, strategy, runner and github.workspace, in any case and in `.` or `[ ]` form, in the workflow's settings, the job's keys, its build steps and its actions' steps (where `inputs.` is the job's own `with:`), the run's GITHUB_ variables (GITHUB_SHA, GITHUB_REF, ...) and git commands that -read the commit, in the text the first pass reads. +read a commit or a ref (log, describe, branch, a revision given to rev-parse or diff, and the like), +in the text the first pass reads. A file a cache step's hashFiles() names is not read; one another +step's names is. And the wiring: each job that uploads an artifact in build-native.yml is one of an artifact's, and each artifact's first job restores it: a native-cache step with `id: native` right after the @@ -87,9 +92,9 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the parts, however this is loaded from native_check import ni # noqa: E402 -from native_check.jobs import discover, each_leg, field, named_crates # noqa: E402 +from native_check.jobs import discover, each_leg, field, moves_cache, named_crates # noqa: E402 from native_check.paths import CARGO_TESTS, MATCHED, code, crossings, names, not_read, scan # noqa: E402 -from native_check.wiring import READS_COMMIT, RUN_VARIABLE, STATUS, check_wiring, expressions, moves_cache, varying # noqa: E402 +from native_check.wiring import RUN_VARIABLE, STATUS, check_wiring, expressions, reads_commit, varying # noqa: E402 def check_reads(artifact, rev): @@ -108,9 +113,9 @@ def check_reads(artifact, rev): f"add it to CARGO_TESTS") for name in sorted(set(RUN_VARIABLE.findall(corpus))): problems.append(f"{artifact}: its job reads GITHUB_{name}, which can change between runs that share a key") - if READS_COMMIT.search(corpus): - problems.append(f"{artifact}: its job reads the commit ({READS_COMMIT.search(corpus).group(0)}), which can " - f"change between runs that share a key") + commit = reads_commit(corpus) + if commit: + problems.append(f"{artifact}: its job reads the commit ({commit}), which can change between runs that share a key") for manifest, step in action_steps: # As in the job: a step that runs after a failure lets the job pass and save what is left. if STATUS.search(field(step, "if")): diff --git a/tools/tests/native_check/jobs.py b/tools/tests/native_check/jobs.py index 28ceb4201..f052d79d4 100644 --- a/tools/tests/native_check/jobs.py +++ b/tools/tests/native_check/jobs.py @@ -39,7 +39,11 @@ CARGO_BUILDS = {"build", "b", "test", "t", "check", "c", "run", "r", "bench", "clippy", "doc", "d", "rustc"} # cargo's subcommands that build no crate of the workspace; any other (a plugin too) may. CARGO_NO_BUILD = {"install", "uninstall", "metadata", "fetch", "fmt", "version", "help", "search", "tree", "update", - "locate-project", "pkgid", "generate-lockfile", "vendor", "new", "init", "login", "logout", "owner"} + "locate-project", "pkgid", "generate-lockfile", "vendor", "new", "init", "login", "logout", "owner", + "clean"} +# The options that take a value before cargo's subcommand and before the command xcrun runs. +CARGO_VALUE_OPTIONS = {"--color", "--config", "-C", "-Z", "--explain"} +XCRUN_VALUE_OPTIONS = {"-sdk", "--sdk", "-toolchain", "--toolchain"} WORKSPACE_PREFIX = re.compile(r"\$\{\{\s*github\.workspace\s*\}\}/|\$\{?(?:GITHUB_WORKSPACE|ROOT|REPO_ROOT|PWD)\}?/") @@ -59,6 +63,9 @@ def field(step, name): return "\n".join(body) following = next((l for l in step[i + 1:] if l.strip()), "") if following and ni.indent(following) > ni.key_indent(line): + if following.lstrip().startswith("- "): + raise ni.Failure(f"`{name}:` lists its items on the next lines; write them on one line, " + f"`{name}: [a, b]`, so they can be read") raise ni.Failure(f"`{name}:` continues on the next lines; write it as `{name}: |` so it can be read") value = re.sub(r"\s+#.*$", "", value).strip() if len(value) > 1 and value[0] == value[-1] and value[0] in "'\"": @@ -123,7 +130,8 @@ def mentions(text, bases, tree, script_dir=None): def shell_commands(script, where): """The commands in shell text, each a list of its words with quotes removed. Commands end at ; & | ( ) ` $( and newlines outside quotes; text inside quotes stays in its word, so a word that - ran something computed keeps its `$`. A backslash escapes a quote, `$`, a space or another + ran something computed keeps its `$`, and the commands of a `$(...)` or backtick substitution in + double quotes are read as commands too. A backslash escapes a quote, `$`, a space or another backslash, and otherwise reads as `/` (the Windows jobs' paths). Heredoc bodies and redirection targets are dropped. An unclosed quote is an error rather than a script swallowed whole.""" commands, words, word, quote, i = [], [], None, None, 0 @@ -151,6 +159,13 @@ def end_command(): if quote: if c == quote: quote = None + elif quote == '"' and (c == "`" or script.startswith("$(", i)): + # A command substitution in double quotes runs its commands; the word keeps its text. + end = backtick_end(script, i + 1, where) if c == "`" else substitution_end(script, i + 2, where) + commands.extend(shell_commands(script[i + (1 if c == "`" else 2):end], where)) + word += script[i:end + 1] + i = end + 1 + continue elif c == "\\" and quote == '"' and nxt in '"$`\\': word += nxt i += 1 @@ -214,6 +229,52 @@ def end_command(): return commands +def substitution_end(script, i, where): + """The index of the `)` that closes the `$(` whose text starts at i, past nested quotes and + substitutions.""" + depth = 1 + while i < len(script): + c = script[i] + if c == "\\": + i += 2 + continue + if c == "'": + i = script.find("'", i + 1) + if i < 0: + break + elif c == '"': + i += 1 + while i < len(script) and script[i] != '"': + if script[i] == "\\": + i += 1 + elif script.startswith("$(", i): + i = substitution_end(script, i + 2, where) + elif script[i] == "`": + i = backtick_end(script, i + 1, where) + i += 1 + elif c == "`": + i = backtick_end(script, i + 1, where) + elif c == "(": + depth += 1 + elif c == ")": + depth -= 1 + if depth == 0: + return i + i += 1 + raise ni.Failure(f"{where}: a `$(` is never closed, so what runs in it cannot be read") + + +def backtick_end(script, i, where): + """The index of the backtick that closes the one before i.""" + while i < len(script): + if script[i] == "\\": + i += 1 + elif script[i] == "`": + return i + i += 1 + raise ni.Failure(f"{where}: a backtick is never closed, so what runs in it cannot be read") + + def is_absolute(token): return token.startswith(("/", "~")) or re.match(r"^[A-Za-z]:/", token) is not None @@ -348,7 +409,6 @@ def walk(script, wd, where, files, guesses, makes, after_cd, followed=False): continue name, args = tokens[0], tokens[1:] base = posixpath.basename(name) - first = next((a for a in args if not a.startswith(("-", "+"))), "") # A make that a wrapper this does not know starts (`chrt 10 make`) would read as an argument. if base not in ("make", "gmake") and base not in NAMES_ONLY and any( posixpath.basename(a) in ("make", "gmake") for a in args): @@ -357,16 +417,11 @@ def walk(script, wd, where, files, guesses, makes, after_cd, followed=False): raise ni.Failure(f"{where}: `{command}` runs what a package manifest says; run the script itself") # Without -p, cargo builds the crate of the dir it runs in, or every member from a dir that # is no crate's; --workspace builds every member wherever it runs. So each build names its - # crates, also behind a launcher (rustup run, xcrun, cross) or a plugin (zigbuild, ndk). - at = next((i for i, t in enumerate(tokens) if posixpath.basename(t) in ("cargo", "cross")), None) - if at is None and is_dynamic(name) and first in CARGO_BUILDS: - at = 0 - if at is not None and base not in NAMES_ONLY: - cargo = tokens[at + 1:] - words = {a for a in cargo if not a.startswith(("-", "+"))} - crates = packages(cargo) - if words and not words & CARGO_NO_BUILD and ( - {"--workspace", "--all"} & set(cargo) or not crates or any(re.search(r"[*?\[]", c) for c in crates)): + # crates. + build = None if base in NAMES_ONLY or base in ("[", "[[", "test") else cargo_build(tokens) + if build is not None: + crates = packages(build) + if {"--workspace", "--all"} & set(build) or not crates or any(re.search(r"[*?\[]", c) for c in crates): raise ni.Failure(f"{where}: `{command}` builds crates it does not name; name each with -p") if name in ("cd", "pushd"): after_cd = True @@ -411,6 +466,33 @@ def walk(script, wd, where, files, guesses, makes, after_cd, followed=False): return after_cd +def cargo_build(tokens): + """The arguments of the cargo command the words run, when it may build a crate: cargo or cross + with a subcommand that builds (any but CARGO_NO_BUILD, a plugin's too), a plugin run by its own + name (cargo-ndk), a variable named for cargo or given a build subcommand (`"$CARGO" ndk`, + `$X build`), behind rustup run or xcrun, or cargo later in the command (`docker run img cargo + build`). None for anything else.""" + name, args = tokens[0], tokens[1:] + base = posixpath.basename(name) + if base == "rustup": + return cargo_build(args[2:]) if len(args) > 2 and args[0] == "run" else None + if base == "xcrun": + while args and args[0].startswith("-"): + args = args[2:] if args[0] in XCRUN_VALUE_OPTIONS else args[1:] + return cargo_build(args) if args else None + if re.match(r"^(?:cargo|cross)-\w", base): + return None if set(args) <= {"--version", "-V", "--help", "-h"} else args + first = next((a for a in args if not a.startswith(("-", "+"))), "") + if not (re.match(r"^(?:cargo|cross)(?:\.exe)?$", base) + or is_dynamic(name) and ("cargo" in name.lower() or first in CARGO_BUILDS)): + at = next((i for i, t in enumerate(args) if posixpath.basename(t) == "cargo"), None) + return None if at is None else cargo_build(args[at:]) + i = 0 + while i < len(args) and args[i].startswith(("-", "+")): + i += 2 if args[i] in CARGO_VALUE_OPTIONS else 1 + return None if i >= len(args) or args[i] in CARGO_NO_BUILD else args[i:] + + def make_command(args, moved, command, where): """([targets], [VAR=value]) of `make [-jN] [VAR=value] ` from the repo root.""" if moved or any(re.match(r"^(-C|-f|--directory|--file|--makefile)", a) for a in args): @@ -513,8 +595,9 @@ def take(step, step_where, scan, values=None): wd, files, step_guesses, make = commands(step, step_where, values) text = "\n".join(step) corpus.append(text) - # What a cache key hashes is not read by the build. - text = re.sub(r"hashFiles\([^)]*\)", "", text) + # What a cache step's key hashes is not read by the build. + if moves_cache(step): + text = re.sub(r"hashFiles\([^)]*\)", "", text) actions.extend(ni.norm(m.group(1)) for m in map(ni.LOCAL_USE.match, step) if m) for p in files: if p not in tree: @@ -621,6 +704,10 @@ def take(step, step_where, scan, values=None): Read = collections.namedtuple("Read", "where text wd values") +def moves_cache(step): + return re.match(r"^actions/cache(/(restore|save))?@", field(step, "uses")) is not None + + def native_cache(steps): """A job's native-cache step, or None.""" return next((s for s in steps if re.search(r"uses:\s*\./\.github/actions/native-cache\b", "\n".join(s))), None) diff --git a/tools/tests/native_check/paths.py b/tools/tests/native_check/paths.py index 0ee93f4b4..8f8819d24 100644 --- a/tools/tests/native_check/paths.py +++ b/tools/tests/native_check/paths.py @@ -19,6 +19,8 @@ "it writes the V8 headers it downloads there"), ("tools/scripts/download-v8.sh", "packages/canvas/src-native/canvas-ios/CanvasNative/include", "it writes the V8 headers it downloads there"), + *(("tools/scripts/build-napi.sh", f"packages/*/platforms/windows/{arch}{files}", "it writes the module it builds there") + for arch in ("x64", "arm64") for files in ("", "/*")), ("crates/canvas-napi/__test__", "packages/canvas", "the tests' titles name the package"), ("packages/canvas/src-native/canvas-ios/CanvasNative/.idea/workspace.xml", "packages/canvas/package.json", "it is the IDE's state, which no build reads"), @@ -67,7 +69,14 @@ def whole(pattern): # A shell's `cd`/`pushd` and where to, and a heredoc's delimiter. CD = re.compile(r"(?:^|[\s;&|(])(?:cd|pushd)\s+(" + WORD + ")") HEREDOC = re.compile(r"(?\[\]|&:!]*/[^\s'\"`=;,(){}<>\[\]|&:!]*") +RUN = re.compile(r"[^\s'\"`=;,(){}<>\[\]|&:!]+") + + +def slashed(text): + """The text's runs of path characters that hold a `/`.""" + return [run for run in RUN.findall(text) if "/" in run] + + # A path given as its segments: path.join(root, 'apps', 'demo'), os.path.join(ROOT, "x"). JOIN = re.compile(r"\b(?:join|resolve)\(([^()]*)\)") WILD = "\x01" @@ -134,18 +143,21 @@ def code(text, p): def expand(text, values): """The text with each variable the file sets replaced by each of its values in turn, and any - other variable (a matrix value too) by WILD.""" - m = VARIABLE.search(text) - if m is None: - return [text] - rests = expand(text[m.end():], values) - name = m.group(1) or m.group(2) or m.group(3) or m.group(4) - options = (values.get(name) if name else None) or [WILD] - if m.group(5): - options = list(dict.fromkeys(options + expand(unquote(m.group(5)), values))) - if len(options) * len(rests) > 64: - options = [WILD] - return [text[:m.start()] + option + rest for option in options for rest in rests] + other variable (a matrix value too) by WILD; from the last variable back, one stands for all its + values (WILD) once there would be more than 64 texts.""" + found = list(VARIABLE.finditer(text)) + rests = [text[found[-1].end():] if found else text] + for i in range(len(found) - 1, -1, -1): + m = found[i] + name = m.group(1) or m.group(2) or m.group(3) or m.group(4) + options = (values.get(name) if name else None) or [WILD] + if m.group(5): + options = list(dict.fromkeys(options + expand(unquote(m.group(5)), values))) + if len(options) * len(rests) > 64: + options = [WILD] + before = text[found[i - 1].end() if i else 0:m.start()] + rests = [before + option + rest for option in options for rest in rests] + return rests def resolve_token(token, here, entries, matched): @@ -267,7 +279,7 @@ def define(name, value): if heredoc is not None: # A heredoc's body is text a command is given (a config file, say), not commands. heredoc = None if line.strip() == heredoc else heredoc - found.update(t for expanded in expand(line, values) for t in TOKEN.findall(expanded)) + found.update(t for expanded in expand(line, values) for t in slashed(expanded)) continue if shell and HEREDOC.search(line): heredoc = HEREDOC.search(line).group(1) @@ -288,10 +300,12 @@ def define(name, value): # As given and from the dir before it, since a popd or subshell may have left that one. dirs += [to] + ([posixpath.join(before, to)] if before and not to.startswith(("/", WILD)) else []) # A value is read where it is exported or given to the command after it (`X=dir cmd`); one - # only set may be a dir the script goes on to name parts of. - rest = SHELL_SET.sub(lambda m: " " + (unquote(m.group(3) or "") if m.group(1) or PREFIX.match(line, m.end()) else ""), line) + # only set may be a dir the script goes on to name parts of, but the commands it runs + # (`X="$(cat f)"`) read. + rest = SHELL_SET.sub(lambda m: " " + (unquote(m.group(3) or "") if m.group(1) or PREFIX.match(line, m.end()) + else ran_in(m.group(3) or "")), line) for expanded in expand(shell_reads(rest) if shell else rest, values): - tokens = TOKEN.findall(expanded) + tokens = slashed(expanded) found.update(tokens) found.update(posixpath.join(d, t) for d in dirs for t in tokens if not t.startswith(("/", WILD))) for m in JOIN.finditer(text): @@ -305,6 +319,11 @@ def unquote(word): return re.sub(r"\"([^\"]*)\"|'([^']*)'", lambda m: m.group(1) if m.group(1) is not None else m.group(2), word) +def ran_in(word): + """The commands a shell word runs, its `$(...)` and backtick substitutions, each after a `;`.""" + return "".join(" ; " + (a or b) for a, b in re.findall(r"\$\((.*)\)|`([^`]*)`", unquote(word))) + + @functools.lru_cache(maxsize=None) def named_paths(rev, p): text = code(texts(rev)[p], p) @@ -358,13 +377,16 @@ def scan(artifact, rev, wanted): in it too large to read that are not binaries. The job pass reads the workflows, actions and Makefile for what the job runs of them.""" tested = set(ni.ARTIFACTS[artifact].get("crates", [])) if artifact in CARGO_TESTS else set() + + def scanned(p): + crate = crate_of(rev, p) + return wanted(p) and not (crate and p[len(crate) + 1:].split("/")[0] in ("tests", "benches", "examples") + and crate not in tested) + problems = [f"{artifact}: {p} is in its key but too large to scan for paths" for p, (_, size) in sorted(blobs(rev).items()) - if size > LIMIT and wanted(p) and textual(p)] + if size > LIMIT and textual(p) and scanned(p)] for p in sorted(texts(rev)): - if p.startswith(".github/workflows/") or re.match(r"^\.github/actions/[^/]+/action\.ya?ml$", p) or p == "Makefile" or not wanted(p): - continue - crate = crate_of(rev, p) - if crate and p[len(crate) + 1:].split("/")[0] in ("tests", "benches", "examples") and crate not in tested: + if p.startswith(".github/workflows/") or re.match(r"^\.github/actions/[^/]+/action\.ya?ml$", p) or p == "Makefile" or not scanned(p): continue problems += crossings(artifact, rev, wanted, p, posixpath.dirname(p), named_paths(rev, p)) return problems diff --git a/tools/tests/native_check/wiring.py b/tools/tests/native_check/wiring.py index a20f6e4ad..c7c73b344 100644 --- a/tools/tests/native_check/wiring.py +++ b/tools/tests/native_check/wiring.py @@ -3,7 +3,7 @@ import re from . import ni -from .jobs import each_leg, field, matrix_values, native_cache, sections +from .jobs import each_leg, field, matrix_values, moves_cache, native_cache, sections GUARD = "steps.native.outputs.hit != 'true'" @@ -16,13 +16,33 @@ RUN_VARIABLE = re.compile(r"\bGITHUB_(SHA|REF|REF_NAME|REF_TYPE|REF_PROTECTED|HEAD_REF|BASE_REF|EVENT_NAME|" r"EVENT_PATH|RUN_ID|RUN_NUMBER|RUN_ATTEMPT|ACTOR|ACTOR_ID|TRIGGERING_ACTOR|WORKFLOW|" r"WORKFLOW_REF|WORKFLOW_SHA|RETENTION_DAYS)\b") -# Git commands whose output is the commit, which differs between commits that share a key. -READS_COMMIT = re.compile(r"\bgit\s+(?:(?:-[Cc]\s+\S+|--\S+)\s+)*" - r"(?:describe|log|show|rev-list|rev-parse\s+(?:--\S+\s+)*(?:HEAD|@)\b)") - - -def moves_cache(step): - return re.match(r"^actions/cache(/(restore|save))?@", field(step, "uses")) is not None +# A git command: its global options, its subcommand and the rest of its command. +GIT = re.compile(r"\bgit((?:[ \t]+(?:-[Cc]|--git-dir|--work-tree|--namespace)[ \t]+\S+|[ \t]+--?[\w-]+(?:=\S*)?)*)" + r"[ \t]+([a-z][\w-]*)([^\n;&|)`]*)") +# git subcommands that read commits or refs, which differ between commits that share a key. +REF_READERS = {"describe", "log", "show", "shortlog", "rev-list", "ls-tree", "cat-file", "name-rev", "symbolic-ref", + "for-each-ref", "show-ref", "show-branch", "merge-base", "reflog", "branch", "tag", "whatchanged", + "blame", "archive", "cherry", "notes", "format-patch", "diff-tree", "diff-index", "bundle", "fast-export"} +# An argument that names a commit. +REVISION = re.compile(r"^(?:HEAD|@|FETCH_HEAD|ORIG_HEAD)(?![\w-])|\w[\^~]|^[0-9a-f]{7,40}$|^(?:origin|upstream|refs)/") + + +def reads_commit(text): + """The first git command in the text that reads a commit or a ref (a revision given to + rev-parse or diff, or a subcommand in REF_READERS), or None.""" + for m in GIT.finditer(text): + command, args, skip = m.group(2), [], False + for word in m.group(3).split(): + if skip: + skip = False + elif re.match(r"^\d*[<>]", word): + skip = re.match(r"^\d*[<>]+$", word) is not None # its target is the next word + elif not word.startswith("-"): + args.append(word.strip("'\"")) + if (command in REF_READERS or command == "rev-parse" and args + or command == "diff" and any(REVISION.search(a) for a in args)): + return m.group(0).strip() + return None def expressions(lines, steps): diff --git a/tools/tests/test_native_inputs.py b/tools/tests/test_native_inputs.py index 54dd30048..a741876d7 100644 --- a/tools/tests/test_native_inputs.py +++ b/tools/tests/test_native_inputs.py @@ -13,6 +13,7 @@ """ import importlib.util import os +import re import shutil import subprocess import sys @@ -110,11 +111,17 @@ def test_cargo_names_every_crate_it_builds(self): ["run: cargo zigbuild --workspace -p a"], ["run: cargo ndk -t arm64-v8a build"], ["run: cargo -Z unstable-options build"], ["run: rustup run nightly cargo build"], ["run: xcrun cargo build"], ["run: cross build"], ['run: "$REAL_CARGO" build'], - ["run: cargo build -p 'canvas-*'"]): + ["run: cargo build -p 'canvas-*'"], ['run: OUT="$(cargo build --message-format=json)"'], + ['run: echo "`cargo build`"'], ["run: cargo-zigbuild build --workspace"], + ["run: cargo-ndk -t arm64-v8a build"], ['run: "$CARGO" ndk -t arm64 build --release'], + ["run: cargo build --features new"], ["run: cargo run --release -- help"], + ["run: cargo test --profile install"], ["run: docker run img cargo build"]): with self.subTest(lines=lines): self.assertRaises(ni.Failure, ran, *lines) for line in ("run: cargo +nightly build -Z build-std=std --target x -p canvas-ios", "run: cargo build -p $CRATE", - "run: cargo install cbindgen@0.29.0 --locked", "run: cargo --version"): + "run: cargo install cbindgen@0.29.0 --locked", "run: cargo --version", "run: cargo clean", + 'run: [ "$MODE" = cross ] && echo cross', "run: cargo-ndk --version", + 'run: LIB="$(cargo build -p canvas-c --message-format=json)"'): with self.subTest(line=line): ran(line) @@ -163,6 +170,10 @@ def test_keys_after_the_steps_are_the_jobs(self): def test_no_steps_is_an_error(self): self.assertRaises(ni.Failure, ni.steps_of, " j:\n steps:\n runs-on: x\n", 4, "test") + def test_a_list_over_lines_is_refused_with_the_form_that_reads(self): + with self.assertRaisesRegex(ni.Failure, re.escape("`needs: [a, b]`")): + jobs.field([" needs:", " - canvas-ios-cache", " - canvas-apple"], "needs") + def test_run_block_with_a_comment_keeps_its_body(self): self.assertEqual(jobs.field([" - run: | # build", " sh x.sh", " #define A 1"], "run"), " sh x.sh\n #define A 1") @@ -208,6 +219,10 @@ def named(text, here="", shell=False): class Paths(unittest.TestCase): + def test_a_long_line(self): + self.assertEqual(len(paths.path_tokens(" ".join(f"$X{i}/a" for i in range(1200)), True)), 1) + self.assertEqual(paths.path_tokens("a" * 200_000, True), ()) + def test_relative_to_the_file_and_after_a_variable(self): cpp = "packages/canvas/platforms/ios/src/cpp" here = "packages/canvas/src-native/android" @@ -326,10 +341,18 @@ def test_an_actions_inputs_are_its_jobs(self): self.assertEqual(wiring.varying(["inputs.save == 'true'"], in_action=True), []) def test_git_commands_that_read_the_commit(self): - for line in ("git describe --tags", 'git -C "$ROOT" rev-parse --short HEAD', "git --no-pager log -1", "git rev-list -1 HEAD"): + for line in ("git describe --tags", 'git -C "$ROOT" rev-parse --short HEAD', "git --no-pager log -1", + "git rev-list -1 HEAD", "git rev-parse @", "git rev-parse --short @", "git rev-parse origin/master", + "git ls-tree HEAD", "git cat-file -p HEAD", "git diff HEAD~1 --stat", "git branch --show-current", + 'V=$(git rev-parse --short=8 "$REF")'): + with self.subTest(line=line): + self.assertTrue(wiring.reads_commit(line)) + for line in ("git rev-parse --show-toplevel", "if git rev-parse --show-toplevel >/dev/null 2>&1; then", + "git rev-parse --show-toplevel 2> /dev/null", "R=$(git rev-parse --show-toplevel)", + "git ls-files Cargo.toml", "git hash-object --stdin", "git diff --exit-code", + "git config --system core.longpaths true", "# the git mode of each entry"): with self.subTest(line=line): - self.assertTrue(wiring.READS_COMMIT.search(line)) - self.assertIsNone(wiring.READS_COMMIT.search("git rev-parse --show-toplevel")) + self.assertIsNone(wiring.reads_commit(line)) IDENTITY = {f"GIT_{who}_{what}": value for who in ("AUTHOR", "COMMITTER") @@ -455,6 +478,30 @@ def test_check_fails_a_read_after_a_quoted_cd(self): "cp ../../../canvas/src-native/canvas-ios/CanvasNative/include/canvas_ios.h x\n") self.assertTrue(any("canvas_ios.h" in p for p in self.problems("canvas-windows", rev))) + def test_check_fails_a_read_in_a_quoted_substitution(self): + script = "tools/scripts/build-napi.sh" + rev = self.commit(script, self.show(script) + '\nV8_TAG="$(cat "$REPO/V8_RELEASE")"\n') + self.assertTrue(any("V8_RELEASE" in p for p in self.problems("canvas-windows", rev))) + + def test_a_large_fixture_of_a_crates_tests_is_not_scanned(self): + rev = self.commit("crates/canvas-svg/tests/big.svg", "\n" * 300_000) + self.assertFalse(any("too large" in p for p in self.problems("canvas-svg-android", rev))) + + def test_check_fails_a_file_a_build_step_hashes(self): + workflow = ".github/workflows/build-native.yml" + text = self.show(workflow) + build = "run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi\n" + self.assertEqual(text.count(build), 1) + rev = self.commit(workflow, text.replace(build, build.replace("run: ", "run: echo ${{ hashFiles('V8_RELEASE') }} && "))) + self.assertTrue(any("V8_RELEASE" in p for p in self.problems("canvas-windows", rev))) + + def test_a_module_build_napi_writes_is_no_read(self): + script = "tools/scripts/build-napi.sh" + rev = self.commit(script, self.show(script).replace('echo "$DEST/$NAME.node"', 'ls -l "$DEST/$NAME.node"; du -sh "$DEST"')) + self.assertEqual(self.problems("canvas-windows", rev), []) + rev = self.commit(script, self.show(script) + '\ncp "$ROOT/packages/canvas/platforms/windows/THIRD_PARTY_NOTICES.txt" "$DEST/x"\n') + self.assertTrue(any("THIRD_PARTY_NOTICES" in p for p in self.problems("canvas-svg-windows", rev))) + def test_check_fails_a_step_of_an_action_that_runs_after_a_failure(self): action = ".github/actions/setup-windows-native/action.yml" text = self.show(action) From 5704276be981e31e7ee556f8b887d7b36ee6a928 Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:05:37 +0800 Subject: [PATCH 09/12] ci: run again with no change to confirm the native outputs restore From c541e9ac16f589995f142892d7a8bf594ee75cc0 Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:11:40 +0800 Subject: [PATCH 10/12] ci: drop the native key script and its lint --- .github/actions/native-cache/action.yml | 96 ---- .github/workflows/build-native.yml | 257 +++------ .github/workflows/npm_release.yml | 31 +- .github/workflows/pull-request.yml | 50 +- tools/scripts/native-inputs.py | 565 ------------------ tools/tests/check-native-inputs.py | 160 ------ tools/tests/native_check/__init__.py | 9 - tools/tests/native_check/jobs.py | 725 ------------------------ tools/tests/native_check/paths.py | 392 ------------- tools/tests/native_check/wiring.py | 235 -------- tools/tests/test_native_inputs.py | 618 -------------------- 11 files changed, 102 insertions(+), 3036 deletions(-) delete mode 100644 .github/actions/native-cache/action.yml delete mode 100644 tools/scripts/native-inputs.py delete mode 100644 tools/tests/check-native-inputs.py delete mode 100644 tools/tests/native_check/__init__.py delete mode 100644 tools/tests/native_check/jobs.py delete mode 100644 tools/tests/native_check/paths.py delete mode 100644 tools/tests/native_check/wiring.py delete mode 100644 tools/tests/test_native_inputs.py diff --git a/.github/actions/native-cache/action.yml b/.github/actions/native-cache/action.yml deleted file mode 100644 index e0e7833cb..000000000 --- a/.github/actions/native-cache/action.yml +++ /dev/null @@ -1,96 +0,0 @@ -name: Native output cache -description: > - Restores a job's finished output when nothing it is built from has changed, so the job can skip - its build (every later step is guarded by `if: steps.native.outputs.hit != 'true'`). The key is - the week plus the hash tools/scripts/native-inputs.py computes; its docstring says what that - covers and why. On a miss the job builds, and the output is saved once the job succeeds, into the - scope of the ref that ran it, so pull requests can restore master's entries. With - NATIVE_CACHE_FRESH=true (the release, or Canvas Native run by hand with `fresh`) it neither - restores nor saves, and the job builds. - - An entry that holds a bad output stays until its week ends: delete it with `gh cache delete ` - (the job's log prints the key), or change the version in the key below to drop every entry. - - An output built by several jobs is restored first, in a job of its own (`restore-only`) that - uploads it on a hit and skips the other jobs. On a miss they build it, and the last of them saves - it under the `key` the first passes on, so both use the same week. - -inputs: - artifact: - description: The job's entry in tools/scripts/native-inputs.py - required: true - path: - description: The finished output, the path the job uploads (or, for a job that uploads nothing, a file it writes when it passes) - required: true - variant: - description: In a matrix job, the matrix as JSON (toJSON of matrix), so every leg gets its own key - required: false - default: '' - restore-only: - description: "'true' in the first job of an output built by several jobs: restore it, but leave the saving to the job that builds it" - required: false - default: 'false' - key: - description: The key the first job of an output built by several jobs computed, in the same run - required: false - default: '' - -outputs: - hit: - description: "'true' when the output was restored and the build can be skipped" - value: ${{ steps.cache.outputs.cache-hit || steps.restore.outputs.cache-hit }} - key: - description: The key, for the jobs that build the output after a miss - value: ${{ inputs.key || steps.key.outputs.key }} - -runs: - using: composite - steps: - - name: Inputs - id: key - if: env.NATIVE_CACHE_FRESH != 'true' && inputs.key == '' - shell: bash - env: - ARTIFACT: ${{ inputs.artifact }} - VARIANT: ${{ inputs.variant }} - # --verbose logs the inputs it hashed, to see why a job missed. Windows runners name it - # `python`. The week bounds how old a reused output can be: crates.io versions and toolchains - # float, and each week's first run of an entry rebuilds it. - run: | - py=python3 - "$py" -c '' 2> /dev/null || py=python - hash=$("$py" tools/scripts/native-inputs.py --verbose --job "$GITHUB_JOB" --variant "$VARIANT" "$ARTIFACT") - leg="" - if [ -n "$VARIANT" ] && [ "$VARIANT" != null ]; then - leg=-$(printf '%s' "$VARIANT" | git hash-object --stdin | cut -c1-12) - fi - week=$(date -u +%G-W%V) - # bump the version to drop every entry - echo "key=native-v1-$week-$ARTIFACT$leg-$hash" >> "$GITHUB_OUTPUT" - - # Exact keys only: an output built from other inputs is never the right one. - - name: Restore - id: cache - if: env.NATIVE_CACHE_FRESH != 'true' && inputs.restore-only != 'true' - uses: actions/cache@v4 - with: - path: ${{ inputs.path }} - key: ${{ inputs.key || steps.key.outputs.key }} - - - name: Restore without saving - id: restore - if: env.NATIVE_CACHE_FRESH != 'true' && inputs.restore-only == 'true' - uses: actions/cache/restore@v4 - with: - path: ${{ inputs.path }} - key: ${{ steps.key.outputs.key }} - - # The last job of an output built by several jobs runs only after its first job missed. A hit - # here means the parts were built for nothing: another run saved the entry meanwhile, or, when - # it repeats, the first job's runner cannot restore what this one saves. - - name: Note an entry the first job missed - if: inputs.key != '' && steps.cache.outputs.cache-hit == 'true' - shell: bash - env: - KEY: ${{ inputs.key }} - run: echo "::warning title=native-cache::restored $KEY, which the first job of this output missed" diff --git a/.github/workflows/build-native.yml b/.github/workflows/build-native.yml index 782509b86..15255e57d 100644 --- a/.github/workflows/build-native.yml +++ b/.github/workflows/build-native.yml @@ -42,16 +42,10 @@ # run the Node-API test suites on the shipped modules (on WARP: runners have no GPU; # audio renders offline and on the 'none' sink: they have no audio device either). # -# Every output is first restored from .github/actions/native-cache, keyed on what it is built from -# (tools/scripts/native-inputs.py says what that covers). On a hit its job skips the build and -# uploads the restored output, so a change rebuilds only the jobs that depend on it: a crate change -# rebuilds every platform that links the crate, a Windows script change only the Windows jobs, and -# a TypeScript change nothing. An output built by several jobs (the Apple xcframeworks) is restored -# by a job of its own on Linux, which on a hit uploads it and skips the jobs that build it: the four -# per-platform jobs and the one that joins their slices. Only that last job saves it, so an -# xcframework is reused only once all five of its macOS jobs have run in one run. A job that builds -# Skia also keeps Skia's built libraries per target in .github/actions/skia-cache, saved only by -# pushes to master. +# The napi-windows modules and the canvas-svg / audio-context mobile builds change rarely, so +# their jobs cache the final artifact keyed on a hash of their sources and skip the whole build +# on a hit. The other jobs that build Skia keep its built libraries per target in +# .github/actions/skia-cache, saved only by pushes to master. name: Build Native permissions: @@ -59,15 +53,10 @@ permissions: on: workflow_call: - inputs: - fresh: - description: Rebuild every output instead of restoring it from .github/actions/native-cache (Skia's prebuilt cache still applies) - type: boolean - default: false env: - # Read by .github/actions/native-cache. - NATIVE_CACHE_FRESH: ${{ inputs.fresh }} + # bump to invalidate the canvas-svg / audio-context / canvas-media artifact caches + NATIVE_CACHE_VERSION: v1 jobs: canvas-android: @@ -75,38 +64,25 @@ jobs: runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 - - uses: ./.github/actions/native-cache - id: native - with: - artifact: canvas-android - path: packages/canvas/platforms/android/canvas-release.aar - uses: ./.github/actions/setup-android-native - if: steps.native.outputs.hit != 'true' - uses: ./.github/actions/skia-cache - if: steps.native.outputs.hit != 'true' with: name: canvas-android - name: Fetch V8 + NativeScript runtime headers - if: steps.native.outputs.hit != 'true' run: ./tools/scripts/download-v8.sh - name: Build libNativeScript.so stub for linking - if: steps.native.outputs.hit != 'true' run: ./tools/scripts/build-android-v8-stub.sh - name: Build Rust libraries - if: steps.native.outputs.hit != 'true' run: make android # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache - if: steps.native.outputs.hit != 'true' with: name: canvas-android save: 'true' - name: Build canvas AAR - if: steps.native.outputs.hit != 'true' working-directory: packages/canvas/src-native/canvas-android run: ./gradlew :canvas:assembleRelease - name: Copy AAR into platforms/android - if: steps.native.outputs.hit != 'true' run: cp packages/canvas/src-native/canvas-android/canvas/build/outputs/aar/canvas-release.aar packages/canvas/platforms/android/canvas-release.aar - uses: actions/upload-artifact@v4 with: @@ -114,38 +90,10 @@ jobs: path: packages/canvas/platforms/android/canvas-release.aar if-no-files-found: error - # The xcframework when nothing it is built from has changed: a hit uploads it here and skips the - # per-platform jobs and canvas-ios, so a lost cache entry cannot fail the run between them. A miss - # leaves canvas-ios to save it under this job's key. On Linux, so a hit takes no macOS runner: - # actions/cache gives Linux and macOS the same version (both zstd), so it restores what canvas-ios - # saved; were it not to, this job would only miss, and the xcframework would build every run. - canvas-ios-cache: - name: Canvas xcframework (cached) - runs-on: ubuntu-22.04 - outputs: - hit: ${{ steps.native.outputs.hit }} - key: ${{ steps.native.outputs.key }} - steps: - - uses: actions/checkout@v4 - - uses: ./.github/actions/native-cache - id: native - with: - artifact: canvas-ios - path: canvas-ios.tar.gz - restore-only: 'true' - - uses: actions/upload-artifact@v4 - if: steps.native.outputs.hit == 'true' - with: - name: canvas-ios - path: canvas-ios.tar.gz - if-no-files-found: error - # One runner per platform: its Rust targets, then its framework slices. The Xcode pre-build # phase reruns cargo for each slice, so the slices are built in the job that owns the target dir. canvas-apple: name: Canvas ${{ matrix.platform }} - needs: canvas-ios-cache - if: needs.canvas-ios-cache.outputs.hit != 'true' runs-on: macos-15 strategy: fail-fast: false @@ -182,38 +130,26 @@ jobs: canvas-ios: name: Canvas xcframework - needs: [canvas-ios-cache, canvas-apple] - if: needs.canvas-ios-cache.outputs.hit != 'true' + needs: canvas-apple runs-on: macos-15 steps: - uses: actions/checkout@v4 - - uses: ./.github/actions/native-cache - id: native - with: - artifact: canvas-ios - path: canvas-ios.tar.gz - key: ${{ needs.canvas-ios-cache.outputs.key }} - uses: maxim-lobanov/setup-xcode@v1 - if: steps.native.outputs.hit != 'true' with: xcode-version: '^16.0' - uses: actions/download-artifact@v4 - if: steps.native.outputs.hit != 'true' with: pattern: canvas-apple-* merge-multiple: true path: slices - name: Unpack slices - if: steps.native.outputs.hit != 'true' run: | mkdir -p packages/canvas/src-native/canvas-ios/dist for f in slices/*.tar.gz; do tar -xzf "$f" -C packages/canvas/src-native/canvas-ios/dist; done - name: Build CanvasNative.xcframework - if: steps.native.outputs.hit != 'true' working-directory: tools/scripts run: sh canvas-build.sh --xcframework - name: Pack xcframework - if: steps.native.outputs.hit != 'true' run: tar -czf canvas-ios.tar.gz -C packages/canvas/platforms/ios/CanvasNativeBinary CanvasNative.xcframework - uses: actions/upload-artifact@v4 with: @@ -226,42 +162,43 @@ jobs: runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 - - uses: ./.github/actions/native-cache - id: native + - name: Restore cached AAR + id: svg-aar + uses: actions/cache@v4 with: - artifact: canvas-svg-android path: packages/canvas-svg/platforms/android/canvassvg-release.aar + key: ${{ env.NATIVE_CACHE_VERSION }}-canvas-svg-android-${{ hashFiles('crates/canvas-svg/**', 'crates/canvas-svg-c/**', 'crates/canvas-svg-android/**', 'crates/canvas-utils/**', 'crates/canvas-core/**', 'crates/gl-bindings/**', 'packages/canvas-svg/src-native/android/**', '!packages/canvas-svg/src-native/android/**/build/**', '!packages/canvas-svg/src-native/android/**/jniLibs/**', 'Cargo.lock', 'tools/scripts/build-svg-android.sh', 'tools/scripts/copy-svg-android.sh', 'Makefile') }} - uses: ./.github/actions/setup-android-native - if: steps.native.outputs.hit != 'true' + if: steps.svg-aar.outputs.cache-hit != 'true' - uses: ./.github/actions/skia-cache - if: steps.native.outputs.hit != 'true' + if: steps.svg-aar.outputs.cache-hit != 'true' with: name: canvas-svg-android # canvassvg's CMake borrows both from packages/canvas (see its CMakeLists.txt) - name: Fetch V8 + NativeScript runtime headers - if: steps.native.outputs.hit != 'true' + if: steps.svg-aar.outputs.cache-hit != 'true' run: ./tools/scripts/download-v8.sh - name: Build libNativeScript.so stub for linking - if: steps.native.outputs.hit != 'true' + if: steps.svg-aar.outputs.cache-hit != 'true' run: ./tools/scripts/build-android-v8-stub.sh - name: Build Rust libraries - if: steps.native.outputs.hit != 'true' + if: steps.svg-aar.outputs.cache-hit != 'true' run: make android-svg # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache - if: steps.native.outputs.hit != 'true' + if: steps.svg-aar.outputs.cache-hit != 'true' with: name: canvas-svg-android save: 'true' - name: Copy .so files into jniLibs - if: steps.native.outputs.hit != 'true' + if: steps.svg-aar.outputs.cache-hit != 'true' run: sh tools/scripts/copy-svg-android.sh - name: Build canvassvg AAR - if: steps.native.outputs.hit != 'true' + if: steps.svg-aar.outputs.cache-hit != 'true' working-directory: packages/canvas-svg/src-native/android run: ./gradlew :canvassvg:assembleRelease - name: Copy AAR into platforms/android - if: steps.native.outputs.hit != 'true' + if: steps.svg-aar.outputs.cache-hit != 'true' run: cp packages/canvas-svg/src-native/android/canvassvg/build/outputs/aar/canvassvg-release.aar packages/canvas-svg/platforms/android/canvassvg-release.aar - uses: actions/upload-artifact@v4 with: @@ -269,32 +206,29 @@ jobs: path: packages/canvas-svg/platforms/android/canvassvg-release.aar if-no-files-found: error - # As canvas-ios-cache: a hit uploads the xcframework and skips the jobs that build it. - canvas-svg-ios-cache: - name: Canvas SVG xcframework (cached) - runs-on: ubuntu-22.04 + # canvas-svg changes rarely: on a hit for its xcframework the per-platform jobs never start. + # The lookup runs on macOS like the restore, so both compute the same cache version. + canvas-svg-cache: + name: Canvas SVG cache lookup + runs-on: macos-15 outputs: - hit: ${{ steps.native.outputs.hit }} - key: ${{ steps.native.outputs.key }} + key: ${{ steps.key.outputs.key }} + hit: ${{ steps.lookup.outputs.cache-hit }} steps: - uses: actions/checkout@v4 - - uses: ./.github/actions/native-cache - id: native + - id: key + run: echo "key=${{ env.NATIVE_CACHE_VERSION }}-canvas-svg-ios-${{ hashFiles('crates/canvas-svg/**', 'crates/canvas-svg-c/**', 'crates/canvas-svg-ios/**', 'crates/canvas-utils/**', 'crates/canvas-core/**', 'packages/canvas-svg/src-native/ios/**', '!packages/canvas-svg/src-native/ios/dist/**', 'Cargo.lock', 'tools/scripts/canvas-svg-build.sh', 'Makefile') }}" >> "$GITHUB_OUTPUT" + - id: lookup + uses: actions/cache/restore@v4 with: - artifact: canvas-svg-ios - path: canvas-svg-ios.tar.gz - restore-only: 'true' - - uses: actions/upload-artifact@v4 - if: steps.native.outputs.hit == 'true' - with: - name: canvas-svg-ios path: canvas-svg-ios.tar.gz - if-no-files-found: error + key: ${{ steps.key.outputs.key }} + lookup-only: true canvas-svg-apple: name: Canvas SVG ${{ matrix.platform }} - needs: canvas-svg-ios-cache - if: needs.canvas-svg-ios-cache.outputs.hit != 'true' + needs: canvas-svg-cache + if: needs.canvas-svg-cache.outputs.hit != 'true' runs-on: macos-15 strategy: fail-fast: false @@ -328,38 +262,38 @@ jobs: canvas-svg-ios: name: Canvas SVG xcframework - needs: [canvas-svg-ios-cache, canvas-svg-apple] - if: needs.canvas-svg-ios-cache.outputs.hit != 'true' + needs: [canvas-svg-cache, canvas-svg-apple] + if: ${{ !cancelled() && needs.canvas-svg-cache.result == 'success' && contains(fromJSON('["success","skipped"]'), needs.canvas-svg-apple.result) }} runs-on: macos-15 steps: - uses: actions/checkout@v4 - - uses: ./.github/actions/native-cache - id: native + - name: Restore cached xcframework + id: svg-xcframework + uses: actions/cache@v4 with: - artifact: canvas-svg-ios path: canvas-svg-ios.tar.gz - key: ${{ needs.canvas-svg-ios-cache.outputs.key }} + key: ${{ needs.canvas-svg-cache.outputs.key }} - uses: maxim-lobanov/setup-xcode@v1 - if: steps.native.outputs.hit != 'true' + if: steps.svg-xcframework.outputs.cache-hit != 'true' with: xcode-version: '^16.0' - uses: actions/download-artifact@v4 - if: steps.native.outputs.hit != 'true' + if: steps.svg-xcframework.outputs.cache-hit != 'true' with: pattern: canvas-svg-apple-* merge-multiple: true path: slices - name: Unpack slices - if: steps.native.outputs.hit != 'true' + if: steps.svg-xcframework.outputs.cache-hit != 'true' run: | mkdir -p packages/canvas-svg/src-native/ios/dist for f in slices/*.tar.gz; do tar -xzf "$f" -C packages/canvas-svg/src-native/ios/dist; done - name: Build CanvasSVG.xcframework - if: steps.native.outputs.hit != 'true' + if: steps.svg-xcframework.outputs.cache-hit != 'true' working-directory: tools/scripts run: sh canvas-svg-build.sh --xcframework - name: Pack xcframework - if: steps.native.outputs.hit != 'true' + if: steps.svg-xcframework.outputs.cache-hit != 'true' run: tar -czf canvas-svg-ios.tar.gz -C packages/canvas-svg/platforms/ios/CanvasSVGBinary CanvasSVG.xcframework - uses: actions/upload-artifact@v4 with: @@ -375,28 +309,29 @@ jobs: with: # Oboe submodules: true - - uses: ./.github/actions/native-cache - id: native + - name: Restore cached AAR + id: audio-aar + uses: actions/cache@v4 with: - artifact: audio-context-android path: packages/audio-context/platforms/android/audiocontext-release.aar + key: ${{ env.NATIVE_CACHE_VERSION }}-audio-context-android-${{ hashFiles('packages/audio-context/src-native/android/**', '!packages/audio-context/src-native/android/**/build/**') }} - uses: actions/setup-java@v4 - if: steps.native.outputs.hit != 'true' + if: steps.audio-aar.outputs.cache-hit != 'true' with: distribution: temurin java-version: '17' # read-only off master, see setup-android-native - uses: gradle/actions/setup-gradle@v4 - if: steps.native.outputs.hit != 'true' + if: steps.audio-aar.outputs.cache-hit != 'true' - name: Setup Android SDK - if: steps.native.outputs.hit != 'true' + if: steps.audio-aar.outputs.cache-hit != 'true' uses: android-actions/setup-android@v4 - name: Build audiocontext AAR - if: steps.native.outputs.hit != 'true' + if: steps.audio-aar.outputs.cache-hit != 'true' working-directory: packages/audio-context/src-native/android run: ./gradlew :audiocontext:assembleRelease - name: Copy AAR into platforms/android - if: steps.native.outputs.hit != 'true' + if: steps.audio-aar.outputs.cache-hit != 'true' run: cp packages/audio-context/src-native/android/audiocontext/build/outputs/aar/audiocontext-release.aar packages/audio-context/platforms/android/audiocontext-release.aar - uses: actions/upload-artifact@v4 with: @@ -407,32 +342,29 @@ jobs: audio-context-ios: name: AudioContext iOS + visionOS + tvOS + Catalyst runs-on: macos-15 - env: - # Bump to rebuild the opus deps. Kept in this job so the bump also misses the job's - # native-cache entry, which keys on the job's own definition. - OPUS_DEPS_CACHE_VERSION: v1 steps: - uses: actions/checkout@v4 - - uses: ./.github/actions/native-cache - id: native + - name: Restore cached xcframework + id: audio-xcframework + uses: actions/cache@v4 with: - artifact: audio-context-ios path: audio-context-ios.tar.gz + key: ${{ env.NATIVE_CACHE_VERSION }}-audio-context-ios-${{ hashFiles('packages/audio-context/src-native/ios/**', 'tools/scripts/audio-context-build.sh') }} - uses: ./.github/actions/setup-apple-native - if: steps.native.outputs.hit != 'true' + if: steps.audio-xcframework.outputs.cache-hit != 'true' with: install-rust: 'false' # libogg / libvorbis / libopus / libopusfile static libs per slice: gitignored, built from # the xiph release tarballs. - name: Restore cached opus deps - if: steps.native.outputs.hit != 'true' + if: steps.audio-xcframework.outputs.cache-hit != 'true' id: opus-deps uses: actions/cache@v4 with: path: packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/third_party/build - key: ${{ env.OPUS_DEPS_CACHE_VERSION }}-audio-context-opus-deps-${{ hashFiles('packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/fetch_opus_deps.sh', 'packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/build_opus_deps_ios.sh') }} + key: ${{ env.NATIVE_CACHE_VERSION }}-audio-context-opus-deps-${{ hashFiles('packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/fetch_opus_deps.sh', 'packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/build_opus_deps_ios.sh') }} - name: Build opus deps - if: steps.native.outputs.hit != 'true' && steps.opus-deps.outputs.cache-hit != 'true' + if: steps.audio-xcframework.outputs.cache-hit != 'true' && steps.opus-deps.outputs.cache-hit != 'true' working-directory: packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative run: | # opusfile's configure finds the ogg and opus it builds against through pkg-config @@ -440,11 +372,11 @@ jobs: ./scripts/build_opus_deps_ios.sh # same as `npm run build.audiocontext.ios.framework.release` - name: Build AudioContextNative.xcframework - if: steps.native.outputs.hit != 'true' + if: steps.audio-xcframework.outputs.cache-hit != 'true' working-directory: tools/scripts run: sh audio-context-build.sh - name: Pack xcframework - if: steps.native.outputs.hit != 'true' + if: steps.audio-xcframework.outputs.cache-hit != 'true' run: tar -czf audio-context-ios.tar.gz -C packages/audio-context/platforms/ios/AudioContextNativeBinary AudioContextNative.xcframework - uses: actions/upload-artifact@v4 with: @@ -468,37 +400,26 @@ jobs: shell: bash steps: - uses: actions/checkout@v4 - - uses: ./.github/actions/native-cache - id: native - with: - artifact: canvas-windows - variant: ${{ toJSON(matrix) }} - path: packages/canvas/platforms/windows/${{ matrix.arch }}/ - uses: ./.github/actions/setup-windows-native - if: steps.native.outputs.hit != 'true' with: target: ${{ matrix.target }} - uses: ./.github/actions/skia-cache - if: steps.native.outputs.hit != 'true' with: name: canvas-windows-${{ matrix.arch }} - uses: actions/setup-node@v4 - if: steps.native.outputs.hit != 'true' with: node-version: '22' - name: Build canvasnative.node (and fetch ANGLE) - if: steps.native.outputs.hit != 'true' run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi # arm64 is cross-compiled, so only x64 runs them. The runners have no GPU: D3D12 and ANGLE # fall back to WARP, and the WebGPU suites skip without an adapter. # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache - if: steps.native.outputs.hit != 'true' with: name: canvas-windows-${{ matrix.arch }} save: 'true' - name: Node-API tests - if: steps.native.outputs.hit != 'true' && matrix.arch == 'x64' + if: matrix.arch == 'x64' env: CANVAS_NAPI_ADDON: ${{ github.workspace }}\packages\canvas\platforms\windows\x64\canvasnative.node run: node --expose-gc --test "crates/canvas-napi/__test__/*.test.mjs" @@ -516,25 +437,29 @@ jobs: fail-fast: false matrix: module: - # `name`-windows is the module's entry in tools/scripts/native-inputs.py. + # `sources`: every tracked directory the module is built from (its cache key). - name: canvas-svg crate: canvas-svg-napi file: canvassvg.node addon-env: CANVAS_SVG_NAPI_ADDON + sources: crates/canvas-svg crates/canvas-svg-c crates/canvas-svg-napi crates/canvas-utils skia: true # Runners have no audio device: its suite renders offline and on the 'none' sink. - name: audio-context crate: audio-context-napi file: audiocontext.node addon-env: AUDIO_CONTEXT_NAPI_ADDON + sources: crates/audio-context-napi - name: canvas-media crate: canvas-media-napi file: canvasmedia.node addon-env: CANVAS_MEDIA_NAPI_ADDON + sources: crates/canvas-media-napi # no Node-API test suite - name: canvas-gamepad crate: canvas-gamepad-napi file: canvasgamepad.node + sources: crates/canvas-gamepad-napi arch: [x64, arm64] include: - arch: x64 @@ -548,37 +473,43 @@ jobs: MODULE_DIR: packages/${{ matrix.module.name }}/platforms/windows/${{ matrix.arch }} steps: - uses: actions/checkout@v4 - - uses: ./.github/actions/native-cache - id: native + # The tree hashes of what the module is built from: equal hashes, equal module. + - name: Source key + id: sources + run: | + key=$(for path in ${{ matrix.module.sources }} crates/vendor/napi-sys Cargo.toml tools/scripts/build-napi.sh; do git rev-parse "HEAD:$path" || exit 1; done | sha256sum | cut -c1-32) + echo "key=$key" >> "$GITHUB_OUTPUT" + - name: Restore cached module + id: cache + uses: actions/cache@v4 with: - artifact: ${{ matrix.module.name }}-windows - variant: ${{ toJSON(matrix) }} - path: ${{ env.MODULE_DIR }}/ + path: ${{ env.MODULE_DIR }}/${{ matrix.module.file }} + key: ${{ env.NATIVE_CACHE_VERSION }}-${{ matrix.module.name }}-windows-${{ matrix.arch }}-${{ steps.sources.outputs.key }} - uses: ./.github/actions/setup-windows-native - if: steps.native.outputs.hit != 'true' + if: steps.cache.outputs.cache-hit != 'true' with: target: ${{ matrix.target }} - uses: ./.github/actions/skia-cache - if: steps.native.outputs.hit != 'true' && matrix.module.skia + if: steps.cache.outputs.cache-hit != 'true' && matrix.module.skia with: name: ${{ matrix.module.name }}-windows-${{ matrix.arch }} - uses: actions/setup-node@v4 - if: steps.native.outputs.hit != 'true' && matrix.arch == 'x64' && matrix.module.addon-env + if: steps.cache.outputs.cache-hit != 'true' && matrix.arch == 'x64' && matrix.module.addon-env with: node-version: '22' - name: Build ${{ matrix.module.file }} - if: steps.native.outputs.hit != 'true' + if: steps.cache.outputs.cache-hit != 'true' run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi ${{ matrix.module.crate }} # arm64 is cross-compiled, so only x64 runs them. The timeout bounds a test process that # hangs on exit (an addon releasing Media Foundation / D3D objects during process shutdown). # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache - if: steps.native.outputs.hit != 'true' && matrix.module.skia + if: steps.cache.outputs.cache-hit != 'true' && matrix.module.skia with: name: ${{ matrix.module.name }}-windows-${{ matrix.arch }} save: 'true' - name: Node-API tests - if: steps.native.outputs.hit != 'true' && matrix.arch == 'x64' && matrix.module.addon-env + if: steps.cache.outputs.cache-hit != 'true' && matrix.arch == 'x64' && matrix.module.addon-env timeout-minutes: 5 run: | export ${{ matrix.module.addon-env }}="$(cygpath -w "$PWD/$MODULE_DIR/${{ matrix.module.file }}")" @@ -604,35 +535,23 @@ jobs: runner: ubuntu-22.04-arm steps: - uses: actions/checkout@v4 - - uses: ./.github/actions/native-cache - id: native - with: - artifact: linux - variant: ${{ toJSON(matrix) }} - path: packages/*/platforms/linux/lib/${{ matrix.arch }}/ - uses: ./.github/actions/setup-linux-native - if: steps.native.outputs.hit != 'true' - uses: ./.github/actions/skia-cache - if: steps.native.outputs.hit != 'true' with: name: linux-${{ matrix.arch }} - uses: actions/setup-node@v4 - if: steps.native.outputs.hit != 'true' with: node-version: '22' - name: Build the Node-API modules - if: steps.native.outputs.hit != 'true' run: ./tools/scripts/build-linux.sh # Mesa's surfaceless EGL (llvmpipe) for 2D / WebGL and lavapipe for WebGPU: no GPU here. # canvas-media's suite drives Media Foundation, so it is Windows only. # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache - if: steps.native.outputs.hit != 'true' with: name: linux-${{ matrix.arch }} save: 'true' - name: Node-API tests - if: steps.native.outputs.hit != 'true' env: CANVAS_NAPI_ADDON: ${{ github.workspace }}/packages/canvas/platforms/linux/lib/${{ matrix.arch }}/canvasnative.node CANVAS_SVG_NAPI_ADDON: ${{ github.workspace }}/packages/canvas-svg/platforms/linux/lib/${{ matrix.arch }}/canvassvg.node diff --git a/.github/workflows/npm_release.yml b/.github/workflows/npm_release.yml index fdde00d3d..d477867b7 100644 --- a/.github/workflows/npm_release.yml +++ b/.github/workflows/npm_release.yml @@ -7,12 +7,9 @@ # Every native artifact build-native.yml produces (Android AARs, iOS/visionOS/tvOS # xcframeworks, Windows and Linux Node-API modules) is built from the tag and placed before # packaging, replacing any committed copy, so npm ships what CI built from the tagged -# sources. `fresh: true` skips the cached outputs that pull requests and master reuse, which -# keep the crates.io versions and toolchains of whenever they were built (Skia's prebuilt -# libraries still restore through skia-cache, as before), and a reused native_run_id must be -# an earlier run of this workflow on the same tag. The committed -# binaries are only what local development uses; the xcframeworks are not committed at all. -# canvas-polyfill's async-release.aar is the one native artifact that still ships as committed. +# sources. The committed binaries are only what local development uses; the xcframeworks +# are not committed at all. canvas-polyfill's async-release.aar is the one native artifact +# that still ships as committed. # # Running on the tag also keeps the build's caches safe: a run can restore master's cache # entries but saves only into its own ref's scope, so nothing a release executes can @@ -47,7 +44,7 @@ on: workflow_dispatch: inputs: native_run_id: - description: 'Reuse native artifacts from this earlier npm Release run of the same tag instead of rebuilding (checked)' + description: 'Reuse native artifacts from this earlier run of the same tag instead of rebuilding' required: false default: '' @@ -86,8 +83,6 @@ jobs: needs: [version] if: inputs.native_run_id == '' uses: ./.github/workflows/build-native.yml - with: - fresh: true publish: runs-on: ubuntu-latest @@ -115,24 +110,6 @@ jobs: corepack install -g npm@11.5.1 test "$(npm --version)" = "11.5.1" - # Master's Canvas Native runs upload artifacts under the same names, but theirs can be - # cached outputs of any age, so only an npm Release run of this tag at this commit may stand - # in: it ran this workflow at this commit, which builds fresh. This identifies the run; it - # cannot see how the run built. Its conclusion is not checked: the usual reason to reuse a - # run is that its publish failed after the native builds succeeded, and - # place-native-artifacts.sh fails on any artifact that is missing. - - name: Check native_run_id - if: inputs.native_run_id != '' - env: - GH_TOKEN: ${{ github.token }} - RUN_ID: ${{ inputs.native_run_id }} - run: | - run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID" --jq '.path + " " + .head_branch + " " + .head_sha') - if [ "$run" != ".github/workflows/npm_release.yml $GITHUB_REF_NAME $GITHUB_SHA" ]; then - echo "::error::native_run_id $RUN_ID is a run of '$run', not of npm_release.yml on $GITHUB_REF_NAME at $GITHUB_SHA" - exit 1 - fi - - name: Download native artifacts uses: actions/download-artifact@v4 with: diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 8ce57f5e8..2b3d19c08 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -2,10 +2,10 @@ # # All native artifacts (Android AARs + iOS/visionOS/tvOS xcframeworks for # canvas, canvas-svg and audio-context; the Windows and Linux x64/arm64 -# Node-API modules) are built by the reusable build-native.yml workflow, or -# restored from its cache when nothing they are built from has changed. On +# Node-API modules) are built by the reusable build-native.yml workflow. On # pushes to master (and manual dispatch) the npm job then packages everything -# with those artifacts and publishes a `pr`-tagged prerelease of each package. +# with those freshly built artifacts and publishes a `pr`-tagged prerelease of +# each package. name: Canvas Native permissions: @@ -17,27 +17,17 @@ on: - master pull_request: workflow_dispatch: - inputs: - fresh: - description: Build every native output instead of restoring it, to check a cached one. Saves no native-cache entry; publishes the prerelease as any dispatch does - type: boolean - default: false - -env: - # Read by .github/actions/native-cache. - NATIVE_CACHE_FRESH: ${{ inputs.fresh }} # A pull request push cancels the run it supersedes. On master a running build finishes (it -# saves the caches pull requests read) and only the newest waiting run starts after it, so runs -# that publish the prerelease, a `fresh` one too, publish in order. +# saves the caches pull requests read) and only the newest waiting push runs after it. concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - # Guards for the class of regression that merges introduce silently (see - # tools/tests/check-v8-bridge-invariants.py), on one Linux runner in a few - # minutes; the native cache check needs the runner's cargo and make. + # Fast, dependency-free guards. These run first because they catch the class + # of regression that merges introduce silently -- see + # tools/tests/check-v8-bridge-invariants.py. static-checks: name: Static Checks runs-on: ubuntu-22.04 @@ -45,28 +35,14 @@ jobs: - uses: actions/checkout@v4 - name: V8 bridge invariants run: python3 tools/tests/check-v8-bridge-invariants.py - # Every native cache key resolves and holds what its job reads, and every cached job skips - # its build on a hit. The npm job waits for this, so a key that misses a read publishes nothing. - - name: Native cache inputs - run: | - python3 tools/tests/test_native_inputs.py - python3 tools/tests/check-native-inputs.py unit-tests: name: Unit Tests runs-on: macos-15 steps: - uses: actions/checkout@v4 - # A pass is cached under the hash of what the tests build from, so unchanged code isn't - # retested. - - uses: ./.github/actions/native-cache - id: native - with: - artifact: unit-tests - path: .native-cache/unit-tests-passed # ~1.8 GB per entry: only master saves one, so pull requests don't crowd the 10 GB cache. - uses: actions/cache/restore@v4 - if: steps.native.outputs.hit != 'true' id: test-cache with: path: | @@ -82,15 +58,11 @@ jobs: # the macOS dylib build, and libtest cannot link against that, so the # rustflags are overridden for this run only. - name: Rust unit tests - if: steps.native.outputs.hit != 'true' env: RUSTFLAGS: '-C link-arg=-undefined -C link-arg=dynamic_lookup' - # The marker the cache saves is the pass: written last, in the same step, after the tests. - run: | - cargo test -p canvas-c --features 2d,webgl,gl - mkdir -p .native-cache && date -u > .native-cache/unit-tests-passed + run: cargo test -p canvas-c --features 2d,webgl,gl - uses: actions/cache/save@v4 - if: steps.native.outputs.hit != 'true' && steps.test-cache.outputs.cache-hit != 'true' && github.event_name == 'push' && github.ref == 'refs/heads/master' + if: steps.test-cache.outputs.cache-hit != 'true' && github.event_name == 'push' && github.ref == 'refs/heads/master' with: path: | ~/.cargo/registry @@ -101,14 +73,12 @@ jobs: build-native: name: Build Native uses: ./.github/workflows/build-native.yml - with: - fresh: ${{ inputs.fresh == true }} npm: name: Npm Build if: ${{ github.event_name != 'pull_request' }} runs-on: ubuntu-22.04 - needs: [static-checks, build-native] + needs: [build-native] env: NPM_TAG: pr # Space separated; must match the packages/ directories. diff --git a/tools/scripts/native-inputs.py b/tools/scripts/native-inputs.py deleted file mode 100644 index abec4c2cd..000000000 --- a/tools/scripts/native-inputs.py +++ /dev/null @@ -1,565 +0,0 @@ -#!/usr/bin/env python3 -"""Computes the cache key of each native build output in CI: a hash of the tracked files the output -may be built from, read from git at a commit, so it is the same on every runner and the working tree -does not affect it. .github/actions/native-cache restores a job's output under this key and skips -the build on a hit; this docstring is the one description of what the key covers. - - native-inputs.py ARTIFACT [REV] the key - native-inputs.py --explain ARTIFACT [REV] each input with its git mode and object id (the key - hashes this) - native-inputs.py --verbose ARTIFACT [REV] the key, with the --explain lines on stderr - native-inputs.py --list the artifact names - --job ID, --variant V as the action passes them: fail unless job ID is one of - ARTIFACT's, and unless a matrix job passes its matrix - -A key covers every tracked file except those the artifact is known not to read, so a file nobody -has placed rebuilds every output rather than none: - * crates: those in its entry in ARTIFACTS and every workspace crate they reach through path - dependencies, as `cargo metadata` reports them for the commit's manifests, with every crate dir - that is not a workspace member and every dir the root Cargo.toml's [patch] and [replace] tables - point a dependency at (crates/vendor), the root Cargo.toml, .cargo/, rust-toolchain* and - Cargo.lock. Of the other members, the dependencies each declares - and its rust-version: Cargo.lock is not committed, so cargo resolves one set of versions for the - whole workspace, and a requirement in any member can move what every build links. An artifact - without crates reads none of these; - * workflows: the blocks of its jobs (build-native.yml's job of the artifact's name, or those its - ARTIFACTS entry lists: the xcframeworks' lookup job and part jobs, for instance) and their - workflows' settings above `jobs:` (comment lines dropped, `run: |` text kept as written), so - editing one job rebuilds only what it builds; no workflow file; - * actions: the dirs of the local actions its jobs use (`uses: ./dir`; naming one any other way is - refused), those they use, and the native-cache action; no other action; - * every other file whose last matching rule in OWNERS names the artifact, or that no rule matches. - -OWNERS and ARTIFACTS are claims about what each job reads. tools/tests/check-native-inputs.py, which -Static Checks runs, holds them to what the jobs are seen to read and checks how the jobs are wired. - -To add a native output, wire its job to .github/actions/native-cache as the check's docstring says, -give it an entry in ARTIFACTS (its crates, and its jobs unless it is build-native.yml's job of its -name), its package dirs in PACKAGE_DIRS, the tools/scripts it runs in SCRIPTS, and add it to the -platform tuples below that hold it. A new crate needs no entry: the closure finds it. A new file -outside the crates is in every key until an OWNERS rule places it. Then run the check: when it -reports a path a file names but its job does not read there (one a script writes, say), add that -to NOT_READ in tools/tests/native_check/paths.py with the reason. - -Crates.io versions float within the declared ranges, and toolchains float within their pins. Neither -is part of the key. The cache action adds the week to the key so nothing reused is more than a week -old, and the release (npm_release.yml) builds with `fresh: true`. - -Needs git, Python 3.8+ and cargo (no network: `metadata --no-deps --offline` fetches nothing). -""" -import argparse -import functools -import hashlib -import io -import json -import os -import posixpath -import re -import subprocess -import sys -import tarfile -import tempfile - -ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -BUILD_NATIVE = ".github/workflows/build-native.yml" -CACHE_ACTION = ".github/actions/native-cache" -NAPI_CRATES = ["crates/canvas-napi", "crates/canvas-svg-napi", "crates/audio-context-napi", - "crates/canvas-media-napi", "crates/canvas-gamepad-napi"] - - -def napi_windows(): - return {"crates": NAPI_CRATES, "jobs": [(BUILD_NATIVE, "napi-windows")]} - - -def apple(artifact, parts, crate): - """An xcframework built in parts: its lookup job, the jobs that build the parts, and its own.""" - return {"crates": [crate], "jobs": [(BUILD_NATIVE, f"{artifact}-cache"), (BUILD_NATIVE, parts), - (BUILD_NATIVE, artifact)]} - - -# crates: the crate dirs it builds. jobs: the workflow and id of each job that builds it, when not -# just build-native.yml's job of the artifact's name. build-napi.sh and build-linux.sh name every -# Node-API crate, so each Node-API build keys them all. -ARTIFACTS = { - "canvas-android": {"crates": ["crates/canvas-android"]}, - "canvas-ios": apple("canvas-ios", "canvas-apple", "crates/canvas-ios"), - "canvas-svg-android": {"crates": ["crates/canvas-svg-android", "crates/canvas-svg-c"]}, - "canvas-svg-ios": apple("canvas-svg-ios", "canvas-svg-apple", "crates/canvas-svg-ios"), - "audio-context-android": {}, - "audio-context-ios": {}, - "canvas-windows": {"crates": NAPI_CRATES}, - "canvas-svg-windows": napi_windows(), - "audio-context-windows": napi_windows(), - "canvas-media-windows": napi_windows(), - "canvas-gamepad-windows": napi_windows(), - "linux": {"crates": NAPI_CRATES}, - "unit-tests": {"crates": ["crates/canvas-c"], "jobs": [(".github/workflows/pull-request.yml", "unit-tests")]}, -} -EVERYONE = tuple(ARTIFACTS) -NONE = () -ANDROID = ("canvas-android", "canvas-svg-android", "audio-context-android") -APPLE = ("canvas-ios", "canvas-svg-ios", "audio-context-ios") -MOBILE = ANDROID + APPLE -WINDOWS = ("canvas-windows", "canvas-svg-windows", "audio-context-windows", "canvas-media-windows", - "canvas-gamepad-windows") -LINUX = ("linux",) -# The jobs that run make, and those that fetch V8's headers and runtime. -MAKE = ("canvas-android", "canvas-ios", "canvas-svg-android", "canvas-svg-ios") -V8 = ("canvas-android", "canvas-ios", "canvas-svg-android") -SCRIPTS = [ - (("canvas-android",), "build-android"), - (("canvas-svg-android",), "build-svg-android copy-svg-android"), - (("canvas-android", "canvas-svg-android"), "build-android-v8-stub"), - (("canvas-ios",), "canvas-build"), - (("canvas-svg-ios",), "canvas-svg-build"), - (("audio-context-ios",), "audio-context-build"), - (V8, "download-v8"), - (WINDOWS, "build-napi download-angle"), - (LINUX, "build-linux"), - # Release steps, which run on what the builds produced, the apps' download of the release's - # frameworks (each release bumps its version), and the maintainers' scripts no job runs. - (NONE, "place-native-artifacts release-ios-binaries download-ios-frameworks release repack android-build " - "copy-android copy-android-libs busy-trace busy-bench build-headers build-ios canvas-build-debug " - "canvas-svg-build-debug"), -] -# The package dirs each build reads: its native sources and the platform dir it writes its output -# to (with the package's app-side files there). On Apple, only the binary's dir: the apps' pods -# compile platforms/ios/src, and no framework build reads it. -PACKAGE_DIRS = { - "canvas-android": ["packages/canvas/src-native/canvas-android", "packages/canvas/platforms/android"], - "canvas-ios": ["packages/canvas/src-native/canvas-ios", "packages/canvas/platforms/ios/CanvasNativeBinary"], - "canvas-svg-android": ["packages/canvas-svg/src-native/android", "packages/canvas-svg/platforms/android"], - "canvas-svg-ios": ["packages/canvas-svg/src-native/ios", "packages/canvas-svg/platforms/ios/CanvasSVGBinary"], - "audio-context-android": ["packages/audio-context/src-native/android", "packages/audio-context/platforms/android"], - "audio-context-ios": ["packages/audio-context/src-native/ios", - "packages/audio-context/platforms/ios/AudioContextNativeBinary"], - "canvas-windows": ["packages/canvas/platforms/windows"], - "canvas-svg-windows": ["packages/canvas-svg/platforms/windows"], - "audio-context-windows": ["packages/audio-context/platforms/windows"], - "canvas-media-windows": ["packages/canvas-media/platforms/windows"], - "canvas-gamepad-windows": ["packages/canvas-gamepad/platforms/windows"], - "linux": ["packages/*/platforms/linux"], -} - -# Which artifacts read the files outside the crates and .github: claims that -# tools/tests/check-native-inputs.py holds the jobs to. The last rule that matches a path decides, -# and a path no rule matches is read by every artifact. A rule is a file or dir (`*` stands for one -# path segment), or `*.ext` for every such file. -OWNERS = [ - # The npm packages' TypeScript, docs and manifests, the demos, the JS tooling, and the patches - # maintainers apply by hand. - *((f"*.{ext}", NONE) for ext in ("ts", "tsx", "js", "jsx", "mjs", "cjs", "css", "scss", "md", "json")), - # The repo's own GitHub settings (its workflows and actions are keyed by job). - (".github", NONE), ("apps", NONE), ("tools/demo", NONE), - ("tools/assets", NONE), ("tools/schematics", NONE), ("tools/tests", NONE), - ("tools/workspace-scripts.js", NONE), ("tools/patches", NONE), ("packages/.gitkeep", NONE), - *((name, NONE) for name in (".editorconfig", ".eslintignore", ".gitignore", ".husky", ".npmrc", ".npsrc", - ".nxignore", ".prettierignore", ".prettierrc", ".travis.yml", ".vscode", ".yarn", - ".yarnrc.yml", "LICENSE")), - # Only audio-context-android checks out a submodule (Oboe). - (".gitmodules", ("audio-context-android",)), - # Only Apple's builds read Swift packages and pods, which name V8's headers too. - ("Makefile", MAKE), ("V8_RELEASE", V8), ("NATIVESCRIPT_IOS_RUNTIME_REF", V8), ("nativescript-v8", V8 + APPLE), - ("CanvasNative.podspec", APPLE), ("NativeScript.podspec", APPLE), ("Package.swift", APPLE), - *((f"tools/scripts/{name}.sh", who) for who, names in SCRIPTS for name in names.split()), - # It only computes the keys. - ("tools/scripts/native-inputs.py", NONE), - # A package's platform dirs hold the files apps build from and the committed outputs; the - # builds read none but their own output's (PACKAGE_DIRS). - ("packages/*/src-native", MOBILE), ("packages/*/platforms", NONE), - # Its native code ships committed (async-release.aar); no job builds it. The others are JavaScript. - ("packages/canvas-polyfill", NONE), - *((f"packages/canvas-{name}", NONE) for name in ("babylon", "chartjs", "phaser", "phaser-ce", "pixi", "three")), - # No job runs it; the Node-API suites are under the crates. - ("packages/canvas-gamepad/__test__", NONE), - *((d, (artifact,)) for artifact, dirs in PACKAGE_DIRS.items() for d in dirs), - # The C++ the Android CMake builds compile; the iOS frameworks do not (the apps' pods do). - ("packages/canvas/platforms/ios/src/cpp", ("canvas-android",)), - ("packages/canvas-svg/platforms/ios/src/cpp", ("canvas-svg-android",)), - # canvassvg's CMake borrows canvas's JNI headers. - ("packages/canvas/src-native/canvas-android/canvas/src/main/cpp", ("canvas-android", "canvas-svg-android")), - # Test fixtures of the Node-API suites, which every Node-API build keys with the crates. - ("apps/demo/src/assets/file-assets/audio", WINDOWS + LINUX), - ("tools/demo/canvas/assets/webgpu/pano.mp4", WINDOWS + LINUX), -] - -RUST_ROOT = re.compile(r"^(Cargo\.toml|Cargo\.lock|rust-toolchain(\.toml)?|\.cargo/.*)$") -# What cargo metadata says of a dependency that can change the versions resolved. -RESOLVES = ("name", "req", "source", "registry", "kind", "target", "optional", "uses_default_features", "features", - "rename") -LOCAL_USE = re.compile(r"^\s*(?:-\s+)?uses:\s*['\"]?\./([^\s'\"@#]+)") -COMMENT = r"(?:\s+#.*)?" - - -class Failure(Exception): - pass - - -def git(*args, data=None, binary=False): - # From the repo's root: ls-tree and archive take paths relative to the dir git runs in. - result = subprocess.run(["git", "-c", "core.quotepath=off", *args], input=data, capture_output=True, cwd=ROOT) - if result.returncode != 0: - raise Failure(f"git {' '.join(args[:2])}: {result.stderr.decode(errors='replace').strip()}") - return result.stdout if binary else result.stdout.decode("utf-8") - - -@functools.lru_cache(maxsize=None) -def show(rev, path): - return git("show", f"{rev}:{path}").replace("\r", "") - - -@functools.lru_cache(maxsize=None) -def tree_entries(rev): - """{path: (type, `mode id`)} of every tree, blob and submodule at rev.""" - entries = {} - for record in git("ls-tree", "-r", "-t", "-z", rev).split("\0"): - if record: - meta, path = record.split("\t", 1) - mode, kind, oid = meta.split() - entries[path] = (kind, f"{mode} {oid}") - return entries - - -@functools.lru_cache(maxsize=None) -def tracked(rev): - return frozenset(p for p, (kind, _) in tree_entries(rev).items() if kind != "tree") - - -def blob_id(text): - data = text.encode("utf-8") - return hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest() - - -def norm(path): - """Resolves . and .. in a repo-relative path; a path above the repo is an error.""" - parts = [] - for part in path.replace("\\", "/").split("/"): - if part in ("", "."): - continue - if part == "..": - if not parts: - raise Failure(f"'{path}' points above the repo") - parts.pop() - else: - parts.append(part) - return "/".join(parts) - - -def matches(rule, path): - if rule.startswith("*."): - return path.endswith(rule[1:]) - want, have = rule.split("/"), path.split("/") - return len(have) >= len(want) and all(w in ("*", h) for w, h in zip(want, have)) - - -@functools.lru_cache(maxsize=None) -def owners(path): - """The artifacts that read a file outside the crates and .github, by OWNERS (cached: after - changing OWNERS, call owners.cache_clear()).""" - found = EVERYONE - for rule, who in OWNERS: - if matches(rule, path): - found = who - return found - - -def indent(line): - return len(line) - len(line.lstrip(" ")) - - -def key_indent(line): - """The column of a line's key, past any `- ` list marker.""" - stripped = line.lstrip(" ") - return indent(line) + len(stripped) - len(stripped.lstrip("- ")) - - -def yaml_lines(text): - """(line, in_scalar) for each line, without YAML comments and blank lines outside block scalars - (`key: |` text), which are kept as written.""" - out, scalar = [], None - for line in text.split("\n"): - if scalar is not None: - if not line.strip() or indent(line) > scalar: - out.append((line, True)) - continue - scalar = None - if not line.strip() or line.lstrip().startswith("#"): - continue - out.append((line, False)) - if re.search(r":\s*[|>][-+0-9]*" + COMMENT + r"\s*$", line): - scalar = key_indent(line) - return out - - -@functools.lru_cache(maxsize=None) -def workflow(path, rev): - """(header, {job id: block}) of a workflow; refuses what a job block would not show.""" - problems, header, jobs, in_jobs, job = [], [], {}, False, None - for line, in_scalar in yaml_lines(show(rev, path)): - if not in_scalar and re.search(r"(:|-)\s+[&*][A-Za-z0-9_][A-Za-z0-9_-]*(\s|$)|<<:", line): - problems.append(f"YAML anchor or alias: {line.strip()}") - if re.match(r"^jobs:" + COMMENT + r"\s*$", line): - in_jobs = True - continue - if not in_jobs: - if "working-directory:" in line and not in_scalar: - problems.append(f"workflow-wide working-directory: {line.strip()}") - header.append(line) - continue - if not in_scalar and re.match(r"^\S", line): - problems.append(f"top-level key after jobs: {line.strip()}") - m = None if in_scalar else re.match(r"^ ([A-Za-z0-9_-]+):" + COMMENT + r"\s*$", line) - if m: - job = m.group(1) - jobs[job] = [] - if job: - jobs[job].append(line) - if problems: - raise Failure(f"{path}: " + "; ".join(problems)) - return "\n".join(header) + "\n", {j: "\n".join(lines) + "\n" for j, lines in jobs.items()} - - -def jobs_of(artifact): - return ARTIFACTS[artifact].get("jobs", [(BUILD_NATIVE, artifact)]) - - -def job_blocks(artifact, rev): - """[(workflow path, job id, the workflow's header, the job's block)] of each job that builds it.""" - out = [] - for path, job_id in jobs_of(artifact): - header, jobs = workflow(path, rev) - if job_id not in jobs: - raise Failure(f"no job '{job_id}' in {path} at {rev}") - out.append((path, job_id, header, jobs[job_id])) - return out - - -def steps_of(text, key_column, where): - """Splits a job block or an action's runs: section at its `steps:` key into (its other lines, the - job-level keys before and after the steps, and [step lines]). Steps may sit two columns in or, - compact, at the key's own column.""" - lines = text.split("\n") - start = next((i for i, line in enumerate(lines) - if re.match(rf"^{' ' * key_column}steps:" + COMMENT + r"\s*$", line)), None) - if start is None: - raise Failure(f"{where}: no steps") - rest = [line for line in lines[start + 1:] if line.strip()] - item = next((" " * c + "- " for c in (key_column + 2, key_column) if rest and rest[0].startswith(" " * c + "- ")), None) - steps, end = [], len(lines) - for i, line in enumerate(lines[start + 1:], start + 1): - if item and line.startswith(item): - steps.append([]) - elif line.strip() and indent(line) <= key_column: - end = i - break - if steps: - steps[-1].append(line) - if not steps: - raise Failure(f"{where}: no steps could be read under `steps:`") - return lines[:start] + lines[end:], steps - - -@functools.lru_cache(maxsize=None) -def crate_dirs(rev): - """Every dir with a Cargo.toml at rev, from git alone, so outputs without crates need no cargo.""" - return tuple(sorted(p[: -len("/Cargo.toml")] for p in tracked(rev) if p.endswith("/Cargo.toml"))) - - -@functools.lru_cache(maxsize=None) -def crate_meta(rev): - """(deps, names, crate dirs, requirements) at rev: each workspace member's path dependencies and - each package name's dir, as `cargo metadata` reports them for the commit's manifests, every dir - with a Cargo.toml, and what decides the versions cargo resolves for the workspace: each member's - declared dependencies and rust-version.""" - tree = tracked(rev) - root = sorted({"Cargo.toml", *(p for p in tree if RUST_ROOT.match(p))}) - archive = git("archive", "--format=tar", rev, "--", *root, *crate_dirs(rev), binary=True) - with tempfile.TemporaryDirectory() as tmp: - with tarfile.open(fileobj=io.BytesIO(archive)) as tar: - if hasattr(tarfile, "data_filter"): - tar.extractall(tmp, filter="data") - else: - tar.extractall(tmp) - try: - # Run outside the repo, so a committed rust-toolchain file does not make rustup install - # its toolchain just to read manifests. - result = subprocess.run(["cargo", "metadata", "--no-deps", "--format-version", "1", "--offline", - "--manifest-path", os.path.join(tmp, "Cargo.toml")], - capture_output=True, stdin=subprocess.DEVNULL, cwd=tempfile.gettempdir()) - except FileNotFoundError: - raise Failure("cargo is not installed") - if result.returncode != 0: - raise Failure(f"cargo metadata at {rev}: {result.stderr.decode(errors='replace').strip()}") - meta = json.loads(result.stdout) - workspace = meta["workspace_root"].replace("\\", "/").rstrip("/") + "/" - - def rel(path): - path = path.replace("\\", "/") - if not path.startswith(workspace): - raise Failure(f"path dependency outside the workspace: {path}") - return path[len(workspace):] - - deps, names, requirements = {}, {}, {} - for package in meta["packages"]: - member = rel(posixpath.dirname(package["manifest_path"].replace("\\", "/"))) - deps[member] = [rel(dep["path"]) for dep in package["dependencies"] if dep.get("path")] - names[package["name"]] = member - # Named fields, so a cargo that reports more of them does not move every key. - declared = [[dep.get(k) for k in RESOLVES] for dep in package["dependencies"]] - requirements[member] = {"rust_version": package.get("rust_version"), "features": package.get("features"), - "dependencies": sorted(declared, key=json.dumps)} - return deps, names, crate_dirs(rev), requirements - - -def closure(rev, start): - """The crate dirs an artifact building start reads: start, the members they reach by path, every - crate dir that is not a member, and the dirs the root manifest patches dependencies to (cargo - metadata reports a patched dependency as a registry one, with no path). Nothing when start is - empty.""" - if not start: - return set() - deps, _, dirs, _ = crate_meta(rev) - seen, queue = set(), list(start) - while queue: - crate = queue.pop() - if crate in seen: - continue - if crate not in deps: - raise Failure(f"{crate} is not a workspace member at {rev}") - seen.add(crate) - queue.extend(deps[crate]) - return seen | {d for d in dirs if d not in deps} | patched(rev) - - -def patched(rev): - """The dirs the root Cargo.toml's [patch.*] and [replace] tables point dependencies at.""" - found, table = set(), "" - for line in show(rev, "Cargo.toml").split("\n"): - header = re.match(r"^\s*\[+\s*([^\]]+?)\s*\]", line) - if header: - table = header.group(1) - elif re.match(r"^(patch\.|replace$)", table): - found.update(norm(p) for _, p in re.findall(r"\bpath\s*=\s*([\"'])(.+?)\1", line)) - return found - - -def used_actions(rev, text, where): - """The local actions a job uses, and those they use, with the native-cache action.""" - found, todo, tree = {CACHE_ACTION}, [text], tracked(rev) - while todo: - for line in todo.pop().split("\n"): - m = LOCAL_USE.match(line) - if m is None and re.search(r"\buses['\"]?\s*:\s*['\"]?\.\.?/", line): - raise Failure(f"{where}: write a local action as `uses: ./dir` on its own line: {line.strip()}") - p = norm(m.group(1)) if m else None - if p is None or p in found: - continue - found.add(p) - manifest = next((f"{p}/{n}" for n in ("action.yml", "action.yaml") if f"{p}/{n}" in tree), None) - if manifest is None: - raise Failure(f"{where}: {p} is used as an action but has no action.yml at {rev}") - todo.append(show(rev, manifest)) - return found - - -def key_filter(artifact, rev): - """Whether a tracked path is one of the artifact's inputs.""" - actions = set().union(*(used_actions(rev, block, f"{path}#{job_id}") for path, job_id, _, block in job_blocks(artifact, rev))) - crates = closure(rev, ARTIFACTS[artifact].get("crates", [])) - dirs = sorted(crate_dirs(rev), key=len, reverse=True) - - def wanted(p): - if p.startswith(".github/workflows/"): - return False - if any(p.startswith(a + "/") for a in actions): - return True - if p.startswith(".github/actions/"): - return False - crate = next((d for d in dirs if p.startswith(d + "/")), None) - if crate is not None: - return crate in crates - if RUST_ROOT.match(p): - return bool(crates) - return artifact in owners(p) - return wanted - - -def key_inputs(artifact, rev): - """The artifact's inputs as `kind id path` lines: each wanted file by its mode and id, a dir whose - files are all wanted by its tree's, the blocks of its jobs and their workflows' headers, and with - crates, what the workspace's resolution reads.""" - wanted, entries = key_filter(artifact, rev), tree_entries(rev) - children = {} - for p in entries: - children.setdefault(posixpath.dirname(p), []).append(p) - - @functools.lru_cache(maxsize=None) - def whole(p): - if entries[p][0] != "tree": - return wanted(p) - return all([whole(c) for c in children[p]]) - - lines = {} - for path, job_id, header, block in job_blocks(artifact, rev): - lines[f"{path}#{job_id}"] = f"block {blob_id(block)}" - lines[f"{path}#header"] = f"block {blob_id(header)}" - if ARTIFACTS[artifact].get("crates"): - lines["Cargo resolution"] = f"deps {blob_id(json.dumps(crate_meta(rev)[3], sort_keys=True))}" - todo = [""] - while todo: - for p in children.get(todo.pop(), []): - if whole(p): - lines[p] = entries[p][1] - elif entries[p][0] == "tree": - todo.append(p) - return "".join(f"{lines[p]} {p}\n" for p in sorted(lines)) - - -def resolve(rev): - try: - return git("rev-parse", "--verify", "--quiet", f"{rev}^{{commit}}").strip() - except Failure: - raise Failure(f"no commit '{rev}'") - - -def main(argv): - parser = argparse.ArgumentParser(prog="native-inputs.py", description="the cache keys of the native build outputs") - mode = parser.add_mutually_exclusive_group() - mode.add_argument("--list", action="store_true") - mode.add_argument("--explain", action="store_true") - mode.add_argument("--verbose", action="store_true") - parser.add_argument("--job") - parser.add_argument("--variant") - parser.add_argument("artifact", nargs="?") - parser.add_argument("rev", nargs="?", default="HEAD") - args = parser.parse_args(argv) - out = sys.stdout.buffer - if args.list: - out.write("".join(f"{a}\n" for a in ARTIFACTS).encode()) - return 0 - if args.artifact not in ARTIFACTS: - raise Failure(f"unknown artifact '{args.artifact}' (one of: {' '.join(ARTIFACTS)})") - rev = resolve(args.rev) - if args.job is not None: - block = next((b for _, job_id, _, b in job_blocks(args.artifact, rev) if job_id == args.job), None) - if block is None: - raise Failure(f"job '{args.job}' does not build '{args.artifact}'") - if (args.variant or "").strip() in ("", "null") and any(re.match(r"^\s+matrix:", l) for l in steps_of(block, 4, args.job)[0]): - raise Failure(f"{args.job} is a matrix job: pass `variant: ${{{{ toJSON(matrix) }}}}`, or its legs share one key") - lines = key_inputs(args.artifact, rev) - if args.explain: - out.write(lines.encode()) - else: - if args.verbose: - sys.stderr.buffer.write(lines.encode()) - out.write((blob_id(lines)[:32] + "\n").encode()) - return 0 - - -if __name__ == "__main__": - try: - sys.exit(main(sys.argv[1:])) - except Failure as error: - sys.stderr.write(f"native-inputs: {error}\n") - sys.exit(1) diff --git a/tools/tests/check-native-inputs.py b/tools/tests/check-native-inputs.py deleted file mode 100644 index b920c13f1..000000000 --- a/tools/tests/check-native-inputs.py +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env python3 -"""Holds the claims tools/scripts/native-inputs.py keys the native builds by (OWNERS, ARTIFACTS and -each artifact's crate closure) to what the jobs are seen to read, and checks that every cached job -is wired to its cache. Static Checks runs it. Its parts are in native_check: jobs.py reads the jobs, -paths.py scans the keys, wiring.py checks the wiring and the values that vary between runs. - - check-native-inputs.py [REV] REV defaults to HEAD - -It is a lint, not a proof. A key leaves out only what OWNERS places elsewhere, the crates outside -its closure, the other jobs' blocks and the actions its jobs do not use, so a job can read what its -key misses only across one of those lines, and two passes look for reads across them; a read -written in a form neither pass follows goes unseen. So OWNERS claims that leave files out are kept -narrow, and a file no rule places is in every key. - -Reading the job: its steps and job-level keys, its actions' steps (with $GITHUB_ACTION_PATH as the -action's dir), the files they run and the files those mention, what `make -n` prints for the targets -it runs, and the scripts in the package dirs OWNERS gives the artifact, followed in turn; the -commands in a `$(...)` or backtick substitution count, in double quotes too. In a job whose legs -build different artifacts, matrix values are this artifact's legs' (the item of a list of maps that -names it in the native-cache `artifact:`). It fails when a file read that way is outside the key, a -crate named that way (by package name or dir) is outside the closure, or the job cannot be read: a -file run that is not tracked, a file a step runs after `cd`, a path above the repo, a script -argument (`bash build`) that is no file, `python -m`, a package runner, cargo building crates it -does not name (these four in followed shell scripts too: any cargo subcommand but those that build -nothing, a plugin's (`cargo ndk`, `cargo-ndk`), one behind rustup run or xcrun, or one run through a -variable (`"$CARGO" build`) too, needs -p for each crate, without a glob, and no --workspace or ---all, wherever it runs), an unclosed quote, substitution or heredoc, a value or list continued on -plain lines, `make` in any form but `make [-jN] [VAR=x] ` from the repo root, a Makefile -with conditionals, includes, $(shell) or paths of the dir it runs in, a Makefile that reads a -variable it does not set (or a `?=` default in a path), which the environment would choose, a -followed script that runs make (but the third-party builds in OWN_MAKE) or sources a computed path -inside the repo, a matrix list over several lines, a local action without action.yml, a workflow key -after `jobs:`, a YAML anchor or alias, or a workflow- or job-wide working-directory. - -Scanning the key: every text file in the key but prose (docs, notices, git's own files), the -workflows, action manifests and Makefile, and the step and job-key text the first pass reads (and a -followed script from the dir a step runs it in), are searched for paths that lead out of the key. A -path counts relative to the repo or to the file's dir, and when it goes up (`..`), from any dir -above the file; from every dir the text has `cd` to, with each of its values; after a variable the -file sets (`set(DIR ...)`, `DIR=...`, the default in `${DIR:-...}`), with each of its values; after -any other variable or a dir named some other way (`${CMAKE_CURRENT_SOURCE_DIR}`, -`env!("CARGO_MANIFEST_DIR")` with `"/../x"`, `format!("{}/x", root)`, `root + '/x'`), from any of -those dirs, with or without the `..` after it; after a compiler flag (`-I`, `-L`, `-F`); with a glob -or another variable (a matrix value too) standing for one path segment, or for the dir it is in when -that matches nothing; given as the segments of a join() or resolve() call; in the values of a CMake -set() list or a shell variable that is exported or given to a command (`DIR=x cmd`), in the commands -a shell variable's value runs (`X="$(cat f)"`), and in a heredoc's body; and naming a dir, for every -file under it, or a crate dir outside the closure (but in a Cargo.toml, which cargo metadata reads). -In shell text, a shell word's quoted and bare parts are one word (`cd "$ROOT"/x`), the script's own -dir (`$(dirname "$0")`) is its dir, a bare word given to a reading command (`ls apps`) is a path, -and what a line only writes (the arguments of mkdir, rm and touch, the destination of cp and the -like, a redirection's target) or prints (echo without a redirection) is not. Comments, by each kind -of file's syntax, are not paths. Crates' tests, benches and examples count only for the jobs in -CARGO_TESTS, which run `cargo test`. A text file in the key over 2 MB that this pass would scan -fails, as it cannot be scanned. This pass holds the claims about build files, such as the C++ the -Android CMake builds compile from the iOS package dir. - -A path a file names but its job does not read there is listed in NOT_READ with the reason, for both -passes. - -Both fail on values that differ between runs that share a key: a ${{ }} context other than matrix, -steps, env, strategy, runner and github.workspace, in any case and in `.` or `[ ]` form, in the -workflow's settings, the job's keys, its build steps and its actions' steps (where `inputs.` is the -job's own `with:`), the run's GITHUB_ variables (GITHUB_SHA, GITHUB_REF, ...) and git commands that -read a commit or a ref (log, describe, branch, a revision given to rev-parse or diff, and the like), -in the text the first pass reads. A file a cache step's hashFiles() names is not read; one another -step's names is. - -And the wiring: each job that uploads an artifact in build-native.yml is one of an artifact's, and -each artifact's first job restores it: a native-cache step with `id: native` right after the -checkout, for its own artifact and the upload's path, with `variant: ${{ toJSON(matrix) }}` in a -matrix job, every later step but the upload skipped on a hit (its `if:` is `steps.native.outputs.hit -!= 'true'`, or that && more, with no ||), and one upload, under its artifact's name. An artifact -built by several jobs (the xcframeworks) has a first job that restores it with `restore-only: -'true'`, only uploads it on a hit, and has the step's `hit` and `key` as outputs. Its other jobs -need the first and have `if: needs..outputs.hit != 'true'` (or that && more, with no ||), and -the last of them needs every other and restores it as above, with `key: ${{ -needs..outputs.key }}`, and saves it. In a matrix job, the `artifact:` of each leg is one of -the job's entries. No job of an artifact, nor a step of its actions, has a status function in an -`if:` or continue-on-error, which run on after a failure and save what is left. No local action's -descriptions hold `${{ }}`, which stop the runner loading it. For the reader, a make target made of -a matrix value counts once per value the strategy lists. - -Needs git, Python 3.8+, cargo and make. -""" -import argparse -import os -import re -import sys - -sys.dont_write_bytecode = True # no __pycache__ beside the parts or the key module -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the parts, however this is loaded - -from native_check import ni # noqa: E402 -from native_check.jobs import discover, each_leg, field, moves_cache, named_crates # noqa: E402 -from native_check.paths import CARGO_TESTS, MATCHED, code, crossings, names, not_read, scan # noqa: E402 -from native_check.wiring import RUN_VARIABLE, STATUS, check_wiring, expressions, reads_commit, varying # noqa: E402 - - -def check_reads(artifact, rev): - """What the artifact's job reads that its key leaves out, by both passes, and the values it - reads that differ between runs that share its key.""" - reads, corpus, action_steps, texts_read = discover(artifact, rev) - wanted = ni.key_filter(artifact, rev) - problems = [f"{artifact}: {how} reads {p}, which its key leaves out (OWNERS gives it to " - f"{', '.join(ni.owners(p)) or 'no artifact'})" for p, how in sorted(reads.items()) - if not wanted(p) and not not_read(how, p)] - crates = ni.closure(rev, ni.ARTIFACTS[artifact].get("crates", [])) - for crate in sorted(named_crates(rev, corpus) - crates): - problems.append(f"{artifact}: its job names {crate}, which is not among its crates in ARTIFACTS") - if artifact not in CARGO_TESTS and re.search(r"\bcargo\s+(?:\+\S+\s+)?(?:test|t|bench)\b", corpus): - problems.append(f"{artifact}: its job runs cargo test, which builds its crates' tests and examples: " - f"add it to CARGO_TESTS") - for name in sorted(set(RUN_VARIABLE.findall(corpus))): - problems.append(f"{artifact}: its job reads GITHUB_{name}, which can change between runs that share a key") - commit = reads_commit(corpus) - if commit: - problems.append(f"{artifact}: its job reads the commit ({commit}), which can change between runs that share a key") - for manifest, step in action_steps: - # As in the job: a step that runs after a failure lets the job pass and save what is left. - if STATUS.search(field(step, "if")): - problems.append(f"{artifact}: {manifest}: `if: {field(step, 'if').strip()}` holds a status function, which " - f"runs it after what it follows failed") - if field(step, "continue-on-error"): - problems.append(f"{artifact}: {manifest}: continue-on-error runs it on after a failure, and the cache saves what is left") - if not moves_cache(step): - for context in varying(expressions([], [step]), in_action=True): - problems.append(f"{artifact}: {manifest} uses {context}, which can change between runs that share a key") - # Matrix values are this artifact's legs' (see discover), so every path counts against its key. - entries, cache = ni.tree_entries(rev), MATCHED.setdefault(rev, {}) - for read in texts_read: - found = names(code(each_leg(read.text, read.values), "step.yml"), read.wd, entries, cache, shell=True) - problems += crossings(artifact, rev, wanted, read.where, read.wd, found - set(reads)) - return problems + scan(artifact, rev, wanted) - - -def main(argv): - parser = argparse.ArgumentParser(prog="check-native-inputs.py", - description="hold the native cache keys to what their jobs read") - parser.add_argument("rev", nargs="?", default="HEAD") - rev, problems = ni.resolve(parser.parse_args(argv).rev), [] - for artifact in ni.ARTIFACTS: - try: - ni.key_inputs(artifact, rev) - problems.extend(check_reads(artifact, rev)) - except ni.Failure as error: - problems.append(f"{artifact}: {error}") - if problems: - raise ni.Failure("\n ".join(["keys:", *problems])) - check_wiring(rev) - print(f"{len(ni.ARTIFACTS)} keys resolve and hold what their jobs read, and every cached job is wired right") - return 0 - - -if __name__ == "__main__": - try: - sys.exit(main(sys.argv[1:])) - except ni.Failure as error: - sys.stderr.write(f"check-native-inputs: {error}\n") - sys.exit(1) diff --git a/tools/tests/native_check/__init__.py b/tools/tests/native_check/__init__.py deleted file mode 100644 index 74818dd64..000000000 --- a/tools/tests/native_check/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -"""The parts of tools/tests/check-native-inputs.py (jobs, paths, wiring) and the key module they hold -the keys of, as `ni`.""" -import importlib.util -import os - -_spec = importlib.util.spec_from_file_location( - "native_inputs", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "scripts", "native-inputs.py")) -ni = importlib.util.module_from_spec(_spec) -_spec.loader.exec_module(ni) diff --git a/tools/tests/native_check/jobs.py b/tools/tests/native_check/jobs.py deleted file mode 100644 index f052d79d4..000000000 --- a/tools/tests/native_check/jobs.py +++ /dev/null @@ -1,725 +0,0 @@ -"""Reads what a native job runs: its steps, the actions they use, the scripts and files they run, -and what `make -n` prints, with the refusals for what cannot be read. The first pass of -tools/tests/check-native-inputs.py, whose docstring says what it checks.""" -import collections -import os -import posixpath -import re -import subprocess -import tempfile - -from . import ni - - -# skia-cache names every platform's build scripts, only to hash them. -SKIA_CACHE = ".github/actions/skia-cache" -# Scripts that build a third-party library from its own sources with its own make. -OWN_MAKE = {f"packages/audio-context/src-native/ios/AudioContextNative/AudioContextNative/scripts/{name}" - for name in ("build_opus_deps.sh", "build_opus_deps_ios.sh")} -SCRIPT_EXT = r"(?:sh|bash|py|js|mjs|cjs|ts|rb|pl|ps1)" -SHELLS = {"sh", "bash", "zsh", "dash", "source", "."} -# The option that makes each interpreter run code given inline rather than a file. -INLINE_CODE = {**{s: {"-c"} for s in SHELLS}, "python": {"-c"}, "python3": {"-c"}, "py": {"-c"}, - "node": {"-e", "--eval", "-p", "--print"}, "ruby": {"-e"}, "perl": {"-e", "-E"}, - "pwsh": {"-Command", "-c", "-EncodedCommand"}, "powershell": {"-Command", "-c", "-EncodedCommand"}} -INTERPRETERS = set(INLINE_CODE) -# Interpreter options whose value is the next argument (so the script is the one after it). -VALUE_OPTIONS = {"-o", "+o", "-O", "+O", "-W", "-X", "-r", "--require", "--import", "--loader", - "-ExecutionPolicy", "-ep"} -# Commands that run the command after them, with their options that take a value. -WRAPPERS = {"sudo": {"-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-U"}, "env": {"-u", "-C", "-S"}, - "nice": {"-n"}, "timeout": {"-s", "-k"}, "time": {"-f", "-o"}, "exec": {"-a"}, - "xargs": {"-n", "-I", "-P", "-L", "-s", "-d", "-E", "-a"}, "nohup": set(), "command": set(), - "arch": set()} -KEYWORDS = {"if", "then", "elif", "else", "while", "until", "do", "!", "{", "}"} -# Commands whose arguments name a program without running it: lookups, output, package installs. -NAMES_ONLY = {"which", "type", "hash", "echo", "printf", "apt", "apt-get", "brew", "choco", "dnf", "yum", - "pacman", "port", "apk", "winget", "zypper"} -PACKAGE_RUNNERS = {"npm", "npx", "yarn", "pnpm", "nx", "bun", "just"} -CARGO_BUILDS = {"build", "b", "test", "t", "check", "c", "run", "r", "bench", "clippy", "doc", "d", "rustc"} -# cargo's subcommands that build no crate of the workspace; any other (a plugin too) may. -CARGO_NO_BUILD = {"install", "uninstall", "metadata", "fetch", "fmt", "version", "help", "search", "tree", "update", - "locate-project", "pkgid", "generate-lockfile", "vendor", "new", "init", "login", "logout", "owner", - "clean"} -# The options that take a value before cargo's subcommand and before the command xcrun runs. -CARGO_VALUE_OPTIONS = {"--color", "--config", "-C", "-Z", "--explain"} -XCRUN_VALUE_OPTIONS = {"-sdk", "--sdk", "-toolchain", "--toolchain"} -WORKSPACE_PREFIX = re.compile(r"\$\{\{\s*github\.workspace\s*\}\}/|\$\{?(?:GITHUB_WORKSPACE|ROOT|REPO_ROOT|PWD)\}?/") - - -def field(step, name): - """A step's `name:` value, inline or as a block scalar; "" when it has none.""" - for i, line in enumerate(step): - m = re.match(rf"^\s*(?:-\s+)?{name}:\s*(.*)$", line) - if not m: - continue - value = m.group(1) - if re.match(r"^[|>][-+0-9]*" + ni.COMMENT + r"\s*$", value): - body = [] - for rest in step[i + 1:]: - if rest.strip() and ni.indent(rest) <= ni.key_indent(line): - break - body.append(rest) - return "\n".join(body) - following = next((l for l in step[i + 1:] if l.strip()), "") - if following and ni.indent(following) > ni.key_indent(line): - if following.lstrip().startswith("- "): - raise ni.Failure(f"`{name}:` lists its items on the next lines; write them on one line, " - f"`{name}: [a, b]`, so they can be read") - raise ni.Failure(f"`{name}:` continues on the next lines; write it as `{name}: |` so it can be read") - value = re.sub(r"\s+#.*$", "", value).strip() - if len(value) > 1 and value[0] == value[-1] and value[0] in "'\"": - value = value[1:-1] - return value - return "" - - -def is_dynamic(token): - return re.search(r"[$*?{}\[\]]", token) is not None - - -def packages(args): - """The crates cargo's -p/--package arguments name.""" - named = [] - for i, a in enumerate(args): - if a in ("-p", "--package") and i + 1 < len(args): - named.append(args[i + 1]) - elif a.startswith("--package="): - named.append(a.split("=", 1)[1]) - elif a.startswith("-p") and not a.startswith("--") and len(a) > 2: - named.append(a[2:]) - return named - - -def looks_like_file(token): - return "/" in token or re.search(r"\." + SCRIPT_EXT + "$", token) is not None - - -# What a script calls its own dir: `$(dirname "$0")`, `$(dirname "${BASH_SOURCE[0]}")`, -# `${BASH_SOURCE[0]%/*}`, `$SCRIPT_DIR`. -SCRIPT_DIR_REF = re.compile(r"\$\(\s*dirname\s+\"?\$(?:0|\{BASH_SOURCE\[0\]\}|BASH_SOURCE)\"?\s*\)" - r"|\$\{BASH_SOURCE\[0\]%/\*\}|\$\{?SCRIPT_DIR\}?") - - -def mentions(text, bases, tree, script_dir=None): - """The tracked files (not dirs) the text names, relative to the repo or to one of bases, and - with script_dir, to what the script calls its own dir. Workflow files are left out: each job's - own block is its input, and a script's message naming the ni.workflow (canvas-build.sh does) would - otherwise rebuild a job for an edit to any other job.""" - found = set() - text = WORKSPACE_PREFIX.sub("", text.replace("\\", "/")) - if script_dir is not None: - text = SCRIPT_DIR_REF.sub("@SCRIPT_DIR@", text) - for token in re.findall(r"[^\s'\"`=;&|()<>,]+", text): - token = token.rstrip(".:") - own = token.startswith("@SCRIPT_DIR@/") - if own: - token = token[len("@SCRIPT_DIR@/"):] - if is_dynamic(token): - continue - for base in ([script_dir] if own else ["", *bases]): - try: - path = ni.norm(posixpath.join(base, token)) - except ni.Failure: - continue - if path in tree and not path.startswith(".github/workflows/"): - found.add(path) - return found - - -def shell_commands(script, where): - """The commands in shell text, each a list of its words with quotes removed. Commands end at - ; & | ( ) ` $( and newlines outside quotes; text inside quotes stays in its word, so a word that - ran something computed keeps its `$`, and the commands of a `$(...)` or backtick substitution in - double quotes are read as commands too. A backslash escapes a quote, `$`, a space or another - backslash, and otherwise reads as `/` (the Windows jobs' paths). Heredoc bodies and redirection - targets are dropped. An unclosed quote is an error rather than a script swallowed whole.""" - commands, words, word, quote, i = [], [], None, None, 0 - heredocs, drop_next = [], False - - def end_word(): - nonlocal word, drop_next - if word is not None: - if drop_next: - drop_next = False - else: - words.append(word) - word = None - - def end_command(): - nonlocal words, drop_next - end_word() - if words: - commands.append(words) - words, drop_next = [], False - - while i < len(script): - c = script[i] - nxt = script[i + 1] if i + 1 < len(script) else "" - if quote: - if c == quote: - quote = None - elif quote == '"' and (c == "`" or script.startswith("$(", i)): - # A command substitution in double quotes runs its commands; the word keeps its text. - end = backtick_end(script, i + 1, where) if c == "`" else substitution_end(script, i + 2, where) - commands.extend(shell_commands(script[i + (1 if c == "`" else 2):end], where)) - word += script[i:end + 1] - i = end + 1 - continue - elif c == "\\" and quote == '"' and nxt in '"$`\\': - word += nxt - i += 1 - else: - word += "/" if c == "\\" else c - elif c == "\\" and nxt and nxt in "'\"$ \\": - word = (word or "") + nxt - i += 1 - elif c in "'\"": - quote, word = c, word or "" - elif c == "#" and word is None: - while i < len(script) and script[i] != "\n": - i += 1 - continue - elif script.startswith("<<", i) and not script.startswith("<<<", i): - end_word() - m = re.match(r"<<-?\s*['\"]?([A-Za-z0-9_]+)['\"]?", script[i:]) - if not m: - raise ni.Failure(f"{where}: cannot read the heredoc at `{script[i:i + 20].strip()}`") - heredocs.append(m.group(1)) - i += m.end() - continue - elif c in "<>": - if word is not None and word.isdigit(): - word = None - end_word() - drop_next = True - while i + 1 < len(script) and script[i + 1] in "<>&": - i += 1 - elif script.startswith(("&&", "||", "$("), i): - end_command() - i += 2 - continue - elif c == "\n": - end_command() - while heredocs: - delimiter = heredocs.pop(0) - i += 1 - while i < len(script): - j = script.find("\n", i) - line = script[i:] if j < 0 else script[i:j] - i = len(script) if j < 0 else j - if line.strip() == delimiter: - break - i += 1 - else: - raise ni.Failure(f"{where}: the heredoc ending `{delimiter}` is not closed") - i -= 1 if i < len(script) else 0 - elif c in ";&|()`": - end_command() - elif c.isspace(): - end_word() - else: - word = (word or "") + ("/" if c == "\\" else c) - i += 1 - if quote: - raise ni.Failure(f"{where}: a {quote} quote is never closed, so what runs after it cannot be read") - if heredocs: - raise ni.Failure(f"{where}: the heredoc ending `{heredocs[0]}` is not closed") - end_command() - return commands - - -def substitution_end(script, i, where): - """The index of the `)` that closes the `$(` whose text starts at i, past nested quotes and - substitutions.""" - depth = 1 - while i < len(script): - c = script[i] - if c == "\\": - i += 2 - continue - if c == "'": - i = script.find("'", i + 1) - if i < 0: - break - elif c == '"': - i += 1 - while i < len(script) and script[i] != '"': - if script[i] == "\\": - i += 1 - elif script.startswith("$(", i): - i = substitution_end(script, i + 2, where) - elif script[i] == "`": - i = backtick_end(script, i + 1, where) - i += 1 - elif c == "`": - i = backtick_end(script, i + 1, where) - elif c == "(": - depth += 1 - elif c == ")": - depth -= 1 - if depth == 0: - return i - i += 1 - raise ni.Failure(f"{where}: a `$(` is never closed, so what runs in it cannot be read") - - -def backtick_end(script, i, where): - """The index of the backtick that closes the one before i.""" - while i < len(script): - if script[i] == "\\": - i += 1 - elif script[i] == "`": - return i - i += 1 - raise ni.Failure(f"{where}: a backtick is never closed, so what runs in it cannot be read") - - -def is_absolute(token): - return token.startswith(("/", "~")) or re.match(r"^[A-Za-z]:/", token) is not None - - -def matrix_values(strategy, artifact=None, named=""): - """{key: [values]} of the values a job's strategy lists for each matrix key: `platform: [ios, - tvos]`, a list of scalars, a list of maps (`module.name`), and include's maps (their own keys). - With an artifact, and named the job's native-cache `artifact:` (`${{ matrix.module.name - }}-windows`), a list of maps keeps only the item that names the artifact: its legs' values.""" - lines = [l for l in strategy if l.strip()] - start = next((i for i, l in enumerate(lines) if re.match(r"^\s+matrix:\s*$", l)), None) - if start is None: - return {} - values, items, key, column = {}, {}, None, None - for line in lines[start + 1:]: - if ni.indent(line) <= ni.indent(lines[start]): - break - column = column if column is not None else ni.indent(line) - m = re.match(r"^\s*(-\s+)?([\w-]+):\s*(.*?)\s*$", line) or re.match(r"^\s*(-\s+)()(.+?)\s*$", line) - if not m: - continue - dash, name, value = m.groups() - if value.startswith(("[", "{")) and not value.endswith(("]", "}")): - raise ni.Failure(f"write the matrix's `{name}:` on one line, so its values can be read: {line.strip()}") - if ni.indent(line) == column and not dash: - key = name - if value.startswith("["): - values[key] = [v.strip().strip("'\"") for v in value.strip("[]").split(",") if v.strip()] - continue - if key is None: - continue - if dash and not name: - values.setdefault(key, []).append(value.strip("'\"")) - continue - if dash: - items.setdefault(key, []).append({}) - field_key = name if key == "include" else f"{key}.{name}" - if value and not value.startswith(("[", "{")): - values.setdefault(field_key, []) - if value.strip("'\"") not in values[field_key]: - values[field_key].append(value.strip("'\"")) - if key in items: - items[key][-1][name] = value.strip("'\"") - for key, maps in items.items(): - own = [m for m in maps if artifact and key != "include" and re.sub( - r"\$\{\{\s*matrix\." + re.escape(key) + r"\.([\w-]+)\s*\}\}", lambda x: m.get(x.group(1), "\x00"), named) == artifact] - if len(own) == 1: - for name in {name for m in maps for name in m}: - if name in own[0]: - values[f"{key}.{name}"] = [own[0][name]] - else: - values.pop(f"{key}.{name}", None) - return values - - -MATRIX = re.compile(r"\$\{\{\s*matrix\.([\w.-]+)\s*\}\}") -MATRIX_WORD = re.compile(r"[^\s'\"]*\x03[\w.-]+\x03[^\s'\"]*") - - -def marked(script): - """The script with each matrix value marked without the spaces `${{ }}` holds, so it stays in - its word.""" - return MATRIX.sub(lambda m: f"\x03{m.group(1)}\x03", script) - - -def unmarked(script): - return re.sub(r"\x03([\w.-]+)\x03", lambda m: "${{ matrix." + m.group(1) + " }}", script) - - -def apart(script): - """(the script without its words that hold a matrix value, and those words, a line each).""" - script = marked(script) - return unmarked(MATRIX_WORD.sub(" ", script)), unmarked("\n".join(MATRIX_WORD.findall(script))) - - -def each_leg(script, values): - """The script with each word that holds a matrix value the strategy lists written once per value, - so `make ${{ matrix.platform }}` reads as one make of every leg's target.""" - script = marked(script) - for key, options in values.items(): - mark = f"\x03{key}\x03" - script = re.sub(r"[^\s'\"]*" + re.escape(mark) + r"[^\s'\"]*", - lambda m: " ".join(m.group(0).replace(mark, v) for v in options), script) - return unmarked(script) - - -def commands(step, where, values=None): - """What a step's run: text runs: (wd, files, guesses, make targets and variables). files must - exist; guesses are (what, path) for a script argument without `/` or extension, which has to.""" - wd = field(step, "working-directory") - files, guesses, makes = set(), [], [] - script = WORKSPACE_PREFIX.sub("", each_leg(re.sub(r"\\\n", " ", field(step, "run")), values or {})) - for line in script.split("\n"): - if re.search(r"(^|[\s;&|(!{])(?:\S*/)?g?make\s[^\n]*(\$\(|`|\$\{\{)", line): - raise ni.Failure(f"{where}: cannot follow make with a computed argument: `{line.strip()}`") - walk(script, wd, where, files, guesses, makes, False) - if len(makes) > 1: - raise ni.Failure(f"{where}: runs make more than once; give each its own step") - return wd, files, guesses, (makes[0] if makes else None) - - -def unwrap(tokens): - """The command a shell command runs, past keywords, assignments and wrappers with their - options; [] for `command -v`, which only looks one up.""" - while tokens: - word = tokens[0] - if word in WRAPPERS: - tokens = tokens[1:] - if word == "command" and tokens and tokens[0] in ("-v", "-V"): - return [] - while tokens and tokens[0].startswith("-"): - option, tokens = tokens[0], tokens[1:] - if option in WRAPPERS[word] and tokens: - tokens = tokens[1:] - if word == "timeout" and tokens and re.match(r"^\d+(\.\d+)?[smhd]?$", tokens[0]): - tokens = tokens[1:] - elif word in KEYWORDS or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", word): - tokens = tokens[1:] - else: - break - return tokens - - -def walk(script, wd, where, files, guesses, makes, after_cd, followed=False): - """What shell text runs, into files, guesses and makes, with the refusals in the docstring. A - followed script is held to the same refusals but may `cd` (the scan follows it); what it runs - is found by its mentions.""" - for tokens in shell_commands(script, where): - command = " ".join(tokens) - tokens = unwrap(tokens) - if not tokens: - continue - name, args = tokens[0], tokens[1:] - base = posixpath.basename(name) - # A make that a wrapper this does not know starts (`chrt 10 make`) would read as an argument. - if base not in ("make", "gmake") and base not in NAMES_ONLY and any( - posixpath.basename(a) in ("make", "gmake") for a in args): - raise ni.Failure(f"{where}: cannot follow the make in `{command}`; run `make ` itself") - if base in PACKAGE_RUNNERS: - raise ni.Failure(f"{where}: `{command}` runs what a package manifest says; run the script itself") - # Without -p, cargo builds the crate of the dir it runs in, or every member from a dir that - # is no crate's; --workspace builds every member wherever it runs. So each build names its - # crates. - build = None if base in NAMES_ONLY or base in ("[", "[[", "test") else cargo_build(tokens) - if build is not None: - crates = packages(build) - if {"--workspace", "--all"} & set(build) or not crates or any(re.search(r"[*?\[]", c) for c in crates): - raise ni.Failure(f"{where}: `{command}` builds crates it does not name; name each with -p") - if name in ("cd", "pushd"): - after_cd = True - elif followed: - if base in ("python", "python3", "py") and "-m" in args: - raise ni.Failure(f"{where}: cannot tell which file `{command.strip()}` runs; run the file itself") - if base in SHELLS and "-c" in args and args.index("-c") + 1 < len(args): - after_cd = walk(args[args.index("-c") + 1], wd, where, files, guesses, makes, after_cd, followed) - elif base in ("make", "gmake"): - makes.append(make_command(args, wd or after_cd, command, where)) - elif base in INTERPRETERS: - if base in ("python", "python3", "py") and "-m" in args: - raise ni.Failure(f"{where}: cannot tell which file `{command.strip()}` runs; run the file itself") - if base in SHELLS and "-c" in args: - code = args[args.index("-c") + 1] if args.index("-c") + 1 < len(args) else "" - after_cd = walk(code, wd, where, files, guesses, makes, after_cd) - continue - if any(a in INLINE_CODE[base] for a in args): - continue - script_arg, skip_value = None, False - for arg in args: - if skip_value: - skip_value = False - elif arg in VALUE_OPTIONS: - skip_value = True - elif not arg.startswith(("-", "+")): - script_arg = arg - break - if script_arg is None or is_dynamic(script_arg) or is_absolute(script_arg): - continue - if after_cd: - raise ni.Failure(f"{where}: runs `{command.strip()}` after `cd`; give the step a working-directory instead") - path = ni.norm(posixpath.join(wd, script_arg)) - if looks_like_file(script_arg): - files.add(path) - else: - guesses.append((f"{where}: `{command.strip()}`", path)) - elif "/" in name and not is_absolute(name) and not is_dynamic(name): - if after_cd: - raise ni.Failure(f"{where}: runs `{name}` after `cd`; give the step a working-directory instead") - files.add(ni.norm(posixpath.join(wd, name))) - return after_cd - - -def cargo_build(tokens): - """The arguments of the cargo command the words run, when it may build a crate: cargo or cross - with a subcommand that builds (any but CARGO_NO_BUILD, a plugin's too), a plugin run by its own - name (cargo-ndk), a variable named for cargo or given a build subcommand (`"$CARGO" ndk`, - `$X build`), behind rustup run or xcrun, or cargo later in the command (`docker run img cargo - build`). None for anything else.""" - name, args = tokens[0], tokens[1:] - base = posixpath.basename(name) - if base == "rustup": - return cargo_build(args[2:]) if len(args) > 2 and args[0] == "run" else None - if base == "xcrun": - while args and args[0].startswith("-"): - args = args[2:] if args[0] in XCRUN_VALUE_OPTIONS else args[1:] - return cargo_build(args) if args else None - if re.match(r"^(?:cargo|cross)-\w", base): - return None if set(args) <= {"--version", "-V", "--help", "-h"} else args - first = next((a for a in args if not a.startswith(("-", "+"))), "") - if not (re.match(r"^(?:cargo|cross)(?:\.exe)?$", base) - or is_dynamic(name) and ("cargo" in name.lower() or first in CARGO_BUILDS)): - at = next((i for i, t in enumerate(args) if posixpath.basename(t) == "cargo"), None) - return None if at is None else cargo_build(args[at:]) - i = 0 - while i < len(args) and args[i].startswith(("-", "+")): - i += 2 if args[i] in CARGO_VALUE_OPTIONS else 1 - return None if i >= len(args) or args[i] in CARGO_NO_BUILD else args[i:] - - -def make_command(args, moved, command, where): - """([targets], [VAR=value]) of `make [-jN] [VAR=value] ` from the repo root.""" - if moved or any(re.match(r"^(-C|-f|--directory|--file|--makefile)", a) for a in args): - raise ni.Failure(f"{where}: only `make ` from the repo root is followed: `{command.strip()}`") - targets, variables, i = [], [], 0 - while i < len(args): - arg = args[i] - if arg in ("-j", "-l") and i + 1 < len(args) and re.match(r"^\d+$", args[i + 1]): - i += 1 - elif "=" in arg and not arg.startswith("-"): - variables.append(arg) - elif not arg.startswith("-"): - targets.append(arg) - i += 1 - if not targets: - raise ni.Failure(f"{where}: name the targets of `{command.strip()}`, so what it runs can be followed") - return targets, variables - - -def make_environment(makefile, variables): - """The variables a Makefile's commands can take from the environment: those it reads but never - sets (a function's own, `$(call f,x)`'s $(1) and $(foreach x,...)'s x, are set, as are a - target's own, `t: X := y`, and `define X`), and its `?=` defaults where they make a path.""" - makefile = makefile.replace("$$", "") - # Not a recipe's (tab-indented) shell assignment, which sets nothing for make. - assignment = r"(?:export[ \t]+|override[ \t]+)?([A-Za-z_][\w.-]*)[ \t]*(?::{1,3}=|\+=|\?=|=)" - set_here = set(re.findall(r"^(?!\t)[ ]*" + assignment, makefile, re.M)) - set_here |= set(re.findall(r"^(?!\t)[^:=#\n]+:(?!=)[ \t]*" + assignment, makefile, re.M)) - set_here |= set(re.findall(r"^define\s+([A-Za-z_][\w.-]*)", makefile, re.M)) - set_here |= {v.split("=", 1)[0] for v in variables} | set(re.findall(r"\$\(foreach\s+([\w.-]+)\s*,", makefile)) - defaults = set(re.findall(r"^\s*([A-Za-z_][\w.-]*)\s*\?=", makefile, re.M)) - found = [] - # $(X), ${X}, $(X:a=b) and $X. - for m in re.finditer(r"\$[({]([A-Za-z_][\w.-]*)(?=[:)}])|\$([A-Za-z_])", makefile): - name = m.group(1) or m.group(2) - if name not in set_here and name not in ("MAKE", "MAKEFLAGS", "MAKECMDGOALS", "SHELL"): - found.append(name) - for name in defaults: - # Next to a path's characters: `dir/$(X)`, `$(X)/lib.a`, `$(X).mk`, `$(X)-out`. - if re.search(rf"[\w./-]\$[({{]{re.escape(name)}[)}}]|\$[({{]{re.escape(name)}[)}}][\w./-]", makefile): - found.append(name) - return sorted(set(found)) - - -def make_commands(rev, targets, variables): - """What `make -n` runs, with the commit's Makefile and no inherited variables. A Makefile that - can run other commands than it prints (conditionals, includes, $(shell)), that names the dir - make runs in, or whose commands the environment can change, is refused.""" - makefile = ni.show(rev, "Makefile") - if re.search(r"^\s*(ifeq|ifneq|ifdef|ifndef|-?include|sinclude)\b|^[^#\n]*!=" - r"|\$[({](shell|origin|wildcard|realpath|abspath|CURDIR)\b", makefile, re.M): - raise ni.Failure("the Makefile has conditionals, includes, $(shell) or paths of the dir make runs " - "in: `make -n` cannot show what a job runs") - for name in make_environment(makefile, variables): - raise ni.Failure(f"the Makefile reads {name} from the environment, which `make -n` does not see: set " - f"it in the Makefile (with =, or ?= where it names no path) or pass it as {name}=...") - with tempfile.TemporaryDirectory() as tmp: - try: - result = subprocess.run(["make", "-n", "-f", "-", *variables, *targets], input=makefile.encode(), - cwd=tmp, capture_output=True, env={"PATH": os.environ.get("PATH", "")}) - except FileNotFoundError: - raise ni.Failure("the job runs make, and make is not installed") - output = result.stdout.decode("utf-8").replace("\r", "") - if os.path.basename(tmp) in output: - raise ni.Failure(f"make -n {' '.join(targets)} prints the dir it ran in, so what it runs cannot be followed") - if result.returncode != 0: - raise ni.Failure(f"make -n {' '.join(targets)}: {result.stderr.decode(errors='replace').strip()}") - return output - - -def named_crates(rev, corpus): - """The members the text names by package name, as a word of its own (`-p canvas-ios`, not - packages/canvas/src-native/canvas-android), or by dir, after any prefix (`$ROOT/crates/x`).""" - _, names, _, _ = ni.crate_meta(rev) - return {member for name, member in names.items() - if re.search(rf"(?)", re.S) -# A shell word: quoted and bare parts with nothing between them (`"$ROOT"/packages/x`). -WORD = r"(?:\"[^\"]*\"|'[^']*'|[^\s;&|()'\"])+" -# Where a file sets a variable to a path: a shell assignment anywhere on a line, CMake's set(), and -# get_filename_component(), whose DIRECTORY or PATH is the dir above the path it is given. -SHELL_SET = re.compile(r"(?:^|[\s;&|()])(export\s+|(?:local|readonly|declare)\s+(?=\w))?([A-Za-z_]\w*)=(" + WORD + ")?") -CMAKE_SET = re.compile(r"^\s*(set|get_filename_component)\(\s*([A-Za-z_]\w*)\s+\"?([^\s\")]+)\"?([^)]*)", re.I) -# A variable: ${{ }}, then the named forms (`${X}`, `$(X)`, `$X`, `${X:-default}`), then any other -# (Ruby's #{x} too). -VARIABLE = re.compile(r"\$\{\{[^}]*\}\}|\$\{([A-Za-z_]\w*)\}|\$\(([A-Za-z_]\w*)\)|\$([A-Za-z_]\w*)" - r"|\$\{([A-Za-z_]\w*):?[-=]([^}]*)\}" - r"|\$\{[^}]*\}|\$\([^)]*\)|#\{[^}]*\}|@[A-Za-z_]\w*@|%[A-Za-z_]\w*%") -# What follows an assignment that a command is given: the command's word on the same line. -PREFIX = re.compile(r"[ \t]+(?![A-Za-z_]\w*=)[^\s;&|()]") -# A shell's `cd`/`pushd` and where to, and a heredoc's delimiter. -CD = re.compile(r"(?:^|[\s;&|(])(?:cd|pushd)\s+(" + WORD + ")") -HEREDOC = re.compile(r"(?\[\]|&:!]+") - - -def slashed(text): - """The text's runs of path characters that hold a `/`.""" - return [run for run in RUN.findall(text) if "/" in run] - - -# A path given as its segments: path.join(root, 'apps', 'demo'), os.path.join(ROOT, "x"). -JOIN = re.compile(r"\b(?:join|resolve)\(([^()]*)\)") -WILD = "\x01" -WILDS = r"[*?" + WILD + "]" -# A value that is a path as written, not a command's output. -PLAIN = re.compile(r"^[\w./@+" + WILD + "-]*$") - - -@functools.lru_cache(maxsize=None) -def blobs(rev): - """{path: (id, size)} of every tracked file at rev.""" - out = {} - for record in ni.git("ls-tree", "-r", "-l", "-z", rev).split("\0"): - if record: - meta, path = record.split("\t", 1) - _, kind, oid, size = meta.split() - if kind == "blob": - out[path] = (oid, int(size)) - return out - - -@functools.lru_cache(maxsize=None) -def texts(rev): - """{path: text} of every tracked text file at rev up to LIMIT.""" - ids = {p: oid for p, (oid, size) in blobs(rev).items() if size <= LIMIT} - missing = sorted({oid for oid in ids.values() if oid not in BLOBS}) - data = ni.git("cat-file", "--batch", data="".join(oid + "\n" for oid in missing).encode(), binary=True) - i = 0 - for oid in missing: - end = data.index(b"\n", i) - size = int(data[i:end].split()[2]) - blob = data[end + 1:end + 1 + size] - i = end + 2 + size - BLOBS[oid] = None if b"\0" in blob[:8000] else blob.decode("utf-8", errors="replace").replace("\r", "") - return {p: BLOBS[oid] for p, oid in ids.items() if BLOBS[oid] is not None} - - -BLOBS = {} # each blob's text, None for a binary, kept across revs -MATCHED = {} # by rev, the paths each pattern with a glob or variable matches - - -SHELL_FILES = (".sh", ".bash", ".zsh") - - -def textual(p): - """Whether p is of a kind of text file whose comments, or prose, this knows (or has no extension): - one too large to scan must not be skipped as if it were binary.""" - name = posixpath.basename(p) - ext = posixpath.splitext(name)[1].lower() - return not ext or name in HASH_NAMES or ext in C_LIKE + HASH + XML + PROSE + (".json", ".svg", ".csv") - - -def code(text, p): - """The file's text without its comments, by the kind of file p is (whole, for a kind whose - comments are not known: a path read for one is the safe mistake); None for prose.""" - name = posixpath.basename(p) - ext = posixpath.splitext(name)[1] - if PROSE_NAMES.match(name) or (ext.lower() in PROSE and name not in HASH_NAMES): - return None - syntax = (C_COMMENT if ext in C_LIKE or ext.lower() in C_LIKE else XML_COMMENT if ext.lower() in XML - else HASH_COMMENT if ext.lower() in HASH or name in HASH_NAMES else None) - return text if syntax is None else syntax.sub(lambda m: " " if m.group(1) else m.group(0), text) - - -def expand(text, values): - """The text with each variable the file sets replaced by each of its values in turn, and any - other variable (a matrix value too) by WILD; from the last variable back, one stands for all its - values (WILD) once there would be more than 64 texts.""" - found = list(VARIABLE.finditer(text)) - rests = [text[found[-1].end():] if found else text] - for i in range(len(found) - 1, -1, -1): - m = found[i] - name = m.group(1) or m.group(2) or m.group(3) or m.group(4) - options = (values.get(name) if name else None) or [WILD] - if m.group(5): - options = list(dict.fromkeys(options + expand(unquote(m.group(5)), values))) - if len(options) * len(rests) > 64: - options = [WILD] - before = text[found[i - 1].end() if i else 0:m.start()] - rests = [before + option + rest for option in options for rest in rests] - return rests - - -def resolve_token(token, here, entries, matched): - """The tracked files and dirs a path in a file can name: from the repo or the file's dir, with - WILD and globs standing for one segment. A path that goes up (`..`), or starts at a dir the file - does not name (an unknown variable, or `"/../x"` after env!("CARGO_MANIFEST_DIR") or the like), - may start from any dir above the file, and after an unknown dir, the `..` may lead anywhere. A - computed name that matches nothing names its dir.""" - token = re.sub(r"^(?:\./)+", "", re.sub(r"^-(?:I|L|F|isystem|iquote|idirafter|include)(?=\S)", "", token)) - # `/x` is a path after a dir the text names some other way (format!("{}/x"), root + '/x') or - # outside the repo, where it matches no tracked entry. - if token.startswith("/") and not token.startswith("//"): - token = WILD + token - unknown = token.startswith(WILD + "/") - token = re.sub(r"^(" + WILD + r"/)+", "", token).rstrip(".") - if token.startswith("/") or "//" in token: - return set() - segments = [s for s in token.split("/") if s] - if not any(re.search(r"[A-Za-z]", s) and not re.search(WILDS, s) for s in segments): - return set() - bases = ["", here] - if unknown or segments[0] == "..": - bases += [here.rsplit("/", n)[0] for n in range(1, here.count("/") + 1)] - forms = [segments] - if unknown and segments[0] == "..": - forms.append(segments[next(i for i, s in enumerate(segments) if s != ".."):]) - found = set() - for base, form in ((b, f) for b in bases for f in forms): - try: - path = ni.norm(posixpath.join(base, *form)) - except ni.Failure: - continue - if not re.search(WILDS, path): - if path in entries: - found.add(path) - continue - parts = path.split("/") - if path not in matched: - pattern = re.compile("^" + "/".join("[^/]*".join(map(re.escape, re.split(WILDS + "+", s))) for s in parts) + "$") - matched[path] = {p for p in entries if pattern.match(p)} - literal = "/".join(parts[:next(i for i, s in enumerate(parts) if re.search(WILDS, s))]) - found |= matched[path] or ({literal} if literal in entries else set()) - return found - - -def names(text, here, entries, matched=None, shell=False): - """The tracked files and dirs the text's paths name (see resolve_token), with matched a cache - for the tree entries come from; shell for shell text (see path_tokens).""" - matched = {} if matched is None else matched - return set().union(*(resolve_token(token, here, entries, matched) for token in path_tokens(text, shell))) - - -# Shell commands whose arguments are paths they write, not read (the last of cp-like ones'), and -# commands that read the paths given to them as bare words (`ls apps`). -WRITES_ALL = {"mkdir", "rm", "rmdir", "touch", "chmod"} -WRITES_LAST = {"cp", "mv", "install", "ln", "rsync"} -PRINTS = {"echo", "printf"} -READS = {"ls", "cat", "cp", "mv", "rsync", "tar", "zip", "find", "du", "stat", "head", "tail", "grep", "sed", "awk", - "cmp", "diff", "sha256sum", "shasum", "md5sum", "xxd", "ln", "source", ".", "bash", "sh", "zsh", "python", - "python3", "node", "file", "readlink", "realpath", "wc", "install"} - - -def shell_reads(line): - """The words of a shell line that can be paths it reads: without what it only writes (the - arguments of mkdir and the like, the destination of cp and the like, a redirection's target) or - prints (echo without a redirection), with the bare words a reading command is given marked as - paths (`./`).""" - kept = [] - for segment in re.split(r"&&|\|\||[;|]", line): - words = segment.split() - while words and re.match(r"^[A-Za-z_]\w*=", words[0]): - words = words[1:] - if not words: - continue - command = posixpath.basename(words[0].strip("'\"")) - redirected = re.search(r"(?", segment) - if command in PRINTS and not redirected: - continue - args = [w for w in words[1:]] - drop = set() - for i, w in enumerate(args): - if w in (">", ">>") and i + 1 < len(args): - drop.add(i + 1) - elif re.match(r"^>>?\S", w): - drop.add(i) - operands = [i for i, w in enumerate(args) if not w.startswith("-") and i not in drop] - if command in WRITES_ALL: - drop.update(operands) - elif command in WRITES_LAST and operands: - target = next((i + 1 for i, w in enumerate(args) if w in ("-t", "--target-directory") and i + 1 < len(args)), None) - drop.add(target if target is not None else operands[-1]) - kept.append(words[0]) - for i, w in enumerate(args): - if i in drop: - continue - bare = command in READS and not w.startswith("-") and "/" not in w and re.search(r"[A-Za-z]", w) - kept.append("./" + w.strip("'\"") if bare else w) - return " ".join(kept) - - -@functools.lru_cache(maxsize=None) -def path_tokens(text, shell=False): - """The paths the text names: its tokens with a `/` (and in shell text, the bare words a reading - command is given, without what a line only writes or prints), with the variables it sets - expanded, the values it gives them and CMake's set() lists, join()'s segments, and each relative - path also from every dir the text has `cd` to. In shell text, the script's own dir is `.`. The - text is code: its comments already gone.""" - values, found, dirs = {}, set(), [] - - def define(name, value): - # A value that is not a plain path (a command's output, say) is unknown. - values.setdefault(name, []) - values[name] += [v if PLAIN.match(v) else WILD for v in expand(unquote(value), values) if v not in values[name]] - - if shell: - text = SCRIPT_DIR_REF.sub(".", re.sub(r"\\\n", " ", text)) - heredoc = None - for line in text.split("\n"): - if heredoc is not None: - # A heredoc's body is text a command is given (a config file, say), not commands. - heredoc = None if line.strip() == heredoc else heredoc - found.update(t for expanded in expand(line, values) for t in slashed(expanded)) - continue - if shell and HEREDOC.search(line): - heredoc = HEREDOC.search(line).group(1) - cmake = CMAKE_SET.match(line) - if cmake: - mode = (cmake.group(4).split() or [""])[0].upper() - define(cmake.group(2), cmake.group(3) + ("/.." if mode in ("DIRECTORY", "PATH") else "")) - # A list's values are what is built from (sources); one value names a dir its uses extend. - line = " ".join(cmake.group(3, 4)) if cmake.group(1).lower() == "set" and cmake.group(4).strip() else "" - for m in SHELL_SET.finditer(line): - define(m.group(2), m.group(3) or "") - for cd in CD.finditer(line): - target, before = unquote(cd.group(1)), dirs[-1] if dirs else None - if target == "-": - continue - for to in expand(target, values): - to = to if PLAIN.match(to) else WILD - # As given and from the dir before it, since a popd or subshell may have left that one. - dirs += [to] + ([posixpath.join(before, to)] if before and not to.startswith(("/", WILD)) else []) - # A value is read where it is exported or given to the command after it (`X=dir cmd`); one - # only set may be a dir the script goes on to name parts of, but the commands it runs - # (`X="$(cat f)"`) read. - rest = SHELL_SET.sub(lambda m: " " + (unquote(m.group(3) or "") if m.group(1) or PREFIX.match(line, m.end()) - else ran_in(m.group(3) or "")), line) - for expanded in expand(shell_reads(rest) if shell else rest, values): - tokens = slashed(expanded) - found.update(tokens) - found.update(posixpath.join(d, t) for d in dirs for t in tokens if not t.startswith(("/", WILD))) - for m in JOIN.finditer(text): - args = [a.strip() for a in m.group(1).split(",")] - found.update(expand("/".join(a[1:-1] if len(a) > 1 and a[0] == a[-1] and a[0] in "'\"" else WILD for a in args), values)) - return tuple(sorted(found)) - - -def unquote(word): - """A shell word without its quotes.""" - return re.sub(r"\"([^\"]*)\"|'([^']*)'", lambda m: m.group(1) if m.group(1) is not None else m.group(2), word) - - -def ran_in(word): - """The commands a shell word runs, its `$(...)` and backtick substitutions, each after a `;`.""" - return "".join(" ; " + (a or b) for a, b in re.findall(r"\$\((.*)\)|`([^`]*)`", unquote(word))) - - -@functools.lru_cache(maxsize=None) -def named_paths(rev, p): - text = code(texts(rev)[p], p) - return frozenset() if text is None else frozenset( - names(text, posixpath.dirname(p), ni.tree_entries(rev), MATCHED.setdefault(rev, {}), p.endswith(SHELL_FILES))) - - -@functools.lru_cache(maxsize=None) -def files_under(rev): - under = collections.defaultdict(list) - for p, (kind, _) in ni.tree_entries(rev).items(): - d = posixpath.dirname(p) if kind != "tree" else None - while d: - under[d].append(p) - d = posixpath.dirname(d) - return under - - -def crate_of(rev, p): - return next((d for d in sorted(ni.crate_meta(rev)[2], key=len, reverse=True) if p.startswith(d + "/")), None) - - -def crossings(artifact, rev, wanted, source, here, targets): - """The targets that source names and the artifact's key leaves out, but source itself and the - dirs it is in, and NOT_READ's. A crate dir counts when it is outside the closure, unless a - Cargo.toml names it (cargo metadata reads those).""" - entries, under, problems = ni.tree_entries(rev), files_under(rev), [] - crate_dirs, crates = ni.crate_meta(rev)[2], ni.closure(rev, ni.ARTIFACTS[artifact].get("crates", [])) - for target in sorted(targets): - if (target == source or target.startswith(".github/workflows/") or here == target - or here.startswith(target + "/") or not_read(source, target)): - continue - if target in crate_dirs: - if target not in crates and posixpath.basename(source) != "Cargo.toml": - problems.append(f"{artifact}: {source} names the crate {target}, which is outside its crates' " - f"closure; if its job does not read it there, add it to NOT_READ with the reason") - continue - left_out = [f for f in (under[target] if entries[target][0] == "tree" else [target]) if not wanted(f)] - if left_out: - first, crate = left_out[0], crate_of(rev, left_out[0]) - whose = (f"{crate} is outside its crates' closure" if crate and crate not in crates else - f"OWNERS gives {first} to {', '.join(ni.owners(first)) or 'no artifact'}") - what = target if left_out == [target] else f"{len(left_out)} of the files under {target}" - problems.append(f"{artifact}: {source} names {what}, which its key leaves out ({whose}); if its " - f"job does not read it there, add it to NOT_READ with the reason") - return problems - - -def scan(artifact, rev, wanted): - """The paths that the text files in the artifact's key name and its key leaves out, and the files - in it too large to read that are not binaries. The job pass reads the workflows, actions and - Makefile for what the job runs of them.""" - tested = set(ni.ARTIFACTS[artifact].get("crates", [])) if artifact in CARGO_TESTS else set() - - def scanned(p): - crate = crate_of(rev, p) - return wanted(p) and not (crate and p[len(crate) + 1:].split("/")[0] in ("tests", "benches", "examples") - and crate not in tested) - - problems = [f"{artifact}: {p} is in its key but too large to scan for paths" for p, (_, size) in sorted(blobs(rev).items()) - if size > LIMIT and textual(p) and scanned(p)] - for p in sorted(texts(rev)): - if p.startswith(".github/workflows/") or re.match(r"^\.github/actions/[^/]+/action\.ya?ml$", p) or p == "Makefile" or not scanned(p): - continue - problems += crossings(artifact, rev, wanted, p, posixpath.dirname(p), named_paths(rev, p)) - return problems diff --git a/tools/tests/native_check/wiring.py b/tools/tests/native_check/wiring.py deleted file mode 100644 index c7c73b344..000000000 --- a/tools/tests/native_check/wiring.py +++ /dev/null @@ -1,235 +0,0 @@ -"""Checks that every native job is wired to its cache and reads no value that changes between runs -of one key. Part of tools/tests/check-native-inputs.py, whose docstring says what it checks.""" -import re - -from . import ni -from .jobs import each_leg, field, matrix_values, moves_cache, native_cache, sections - - -GUARD = "steps.native.outputs.hit != 'true'" -# A context in an expression, with the field it reads (`.x` or `['x']`), if any. -CONTEXT = re.compile(r"(?]", word): - skip = re.match(r"^\d*[<>]+$", word) is not None # its target is the next word - elif not word.startswith("-"): - args.append(word.strip("'\"")) - if (command in REF_READERS or command == "rev-parse" and args - or command == "diff" and any(REVISION.search(a) for a in args)): - return m.group(0).strip() - return None - - -def expressions(lines, steps): - """The ${{ }} expressions in the lines and steps, with each step's bare `if:`.""" - texts = [*lines, *("\n".join(step) for step in steps)] - return [e for text in texts for e in re.findall(r"\$\{\{(.*?)\}\}", text)] + [field(step, "if") for step in steps] - - -def varying(found, in_action=False): - """The contexts the expressions read that can differ between runs of a job leg. In an action, - `inputs.` is the job's own `with:`, which is checked where the job is.""" - out = [] - for expression in found: - for m in CONTEXT.finditer(expression): - name, key = m.group(1).lower(), re.sub(r"[\s.\[\]']", "", m.group(2) or "").lower() - if not (name in STEADY_CONTEXTS or (name, key) == ("github", "workspace") or (name == "inputs" and in_action)): - out.append(" ".join(m.group(0).split())) - return out - - -def check_wiring(rev): - """Each job that uploads an artifact in build-native.yml is one of an artifact's, and each - artifact's jobs cache it. Its first job restores it: a native-cache step with `id: native` right - after the checkout, for that artifact and the upload's path, `variant: ${{ toJSON(matrix) }}` in - a matrix job, and every later step but the upload skipped on a hit. An artifact built by several - jobs is restored with `restore-only: 'true'` by a first job that only uploads it on a hit and has - the step's `hit` and `key` as outputs; its other jobs need that job and are skipped on its hit, - and the last of them restores it as above, under the first job's key, and saves it. No job of an - artifact uses a value that changes from run to run where it could change what is built, nor a - status function (success(), always(), cancelled(), failure()) in an `if:`, which would run a - step or job after one it follows failed. Each build-native.yml job that restores an output - uploads it once, under its artifact's name. And no local action's descriptions hold `${{ }}`: - the runner evaluates them and cannot load the action.""" - problems, artifacts_of, parsed = [], {}, {} - for manifest in sorted(p for p in ni.tracked(rev) if re.match(r"^\.github/actions/[^/]+/action\.ya?ml$", p)): - column = None - for line in ni.show(rev, manifest).split("\nruns:")[0].split("\n"): - if column is not None and line.strip() and ni.indent(line) <= column: - column = None - if re.match(r"^\s*description:", line): - column = ni.indent(line) - if column is not None and "${{" in line: - problems.append(f"{manifest}: an expression in an action's description stops the runner loading it: {line.strip()}") - for artifact in ni.ARTIFACTS: - for job in ni.jobs_of(artifact): - artifacts_of.setdefault(job, []).append(artifact) - for path in sorted({p for p, _ in artifacts_of} | {ni.BUILD_NATIVE}): - header, jobs = ni.workflow(path, rev) - settings = [l for l in sections(header.split("\n"), 0, {"env", "defaults"}) - if l.strip() != "NATIVE_CACHE_FRESH: ${{ inputs.fresh }}"] - for job_id, block in jobs.items(): - where = f"{path}#{job_id}" - try: - outside, steps = ni.steps_of(block, 4, where) - except ni.Failure: - if (path, job_id) in artifacts_of: - raise - continue - cache = native_cache(steps) - uploads = [s for s in steps if re.match(r"^actions/upload-artifact@", field(s, "uses"))] - if (path, job_id) not in artifacts_of: - if path == ni.BUILD_NATIVE and (uploads or cache): - problems.append(f"{where}: builds an artifact, but no entry in ARTIFACTS lists this job") - continue - parsed[path, job_id] = (where, outside, steps, cache, uploads) - # Steps that only move caches, like the upload, do not change what is built; nor do the - # header's and the job's keys other than these. - builds = [s for s in steps if s is not cache and s not in uploads and not moves_cache(s)] - job_settings = settings + sections(outside, 4, {"runs-on", "env", "defaults", "strategy", "container", "services"}) - for context in varying(expressions(job_settings, builds)): - problems.append(f"{where}: uses {context}, which can change between runs that share a key") - for condition in [job_key(outside, "if"), *(field(s, "if") for s in steps)]: - if STATUS.search(condition): - problems.append(f"{where}: `if: {condition.strip()}` holds a status function, which runs it after " - f"what it follows failed") - # It runs what follows a failure, and saves the cache with whatever the failed step left. - if job_key(outside, "continue-on-error") or any(field(s, "continue-on-error") for s in steps): - problems.append(f"{where}: continue-on-error runs it on after a failure, and the cache saves what is left") - if cache is None: - continue - if field(cache, "id") != "native": - problems.append(f"{where}: the native-cache step needs `id: native`") - artifact = field(cache, "artifact") - # In a matrix job, each leg's: an entry no leg names is never built, and a leg no entry - # lists has no key. - for leg in sorted(set(each_leg(artifact, matrix_values(outside)).split()) - set(artifacts_of[path, job_id])): - problems.append(f"{where}: native-cache artifact '{leg}' is not one of this job's entries") - if any(not re.match(r"^actions/checkout@", field(s, "uses")) for s in steps[:steps.index(cache)]): - problems.append(f"{where}: only the checkout may come before the native-cache step") - if any(re.match(r"^\s+matrix:", l) for l in outside) and re.sub(r"\s", "", field(cache, "variant")) != "${{toJSON(matrix)}}": - problems.append(f"{where}: a matrix job passes `variant: ${{{{ toJSON(matrix) }}}}`") - for artifact in ni.ARTIFACTS: - jobs = ni.jobs_of(artifact) - if any(job not in parsed for job in jobs): - continue - cached = [job for job in jobs if parsed[job][3] is not None] - firsts = [job for job in cached if not field(parsed[job][3], "key")] - if len(firsts) != 1: - problems.append(f"{artifact}: one of its jobs restores it under the key it computes") - continue - first = firsts[0] - where, outside, steps, cache, uploads = parsed[first] - if len(jobs) == 1: - if field(cache, "restore-only"): - problems.append(f"{where}: an output built by one job is restored and saved there, without restore-only") - problems += restored(*parsed[first], uploaded=first[0] == ni.BUILD_NATIVE) - continue - if field(cache, "restore-only") != "true": - problems.append(f"{where}: {artifact} is built by several jobs, so its first job passes `restore-only: 'true'`") - outputs = dict(m.groups() for m in (re.match(r"^\s+([\w-]+):\s*(.*?)\s*$", l) - for l in sections(outside, 4, {"outputs"})[1:]) if m) - for name in ("hit", "key"): - if re.sub(r"\s", "", outputs.get(name, "")) != f"${{{{steps.native.outputs.{name}}}}}": - problems.append(f"{where}: its outputs are `{name}: ${{{{ steps.native.outputs.{name} }}}}`") - after = steps[steps.index(cache) + 1:] - if len(after) != 1 or after[0] not in uploads or bare(field(after[0], "if")) != "steps.native.outputs.hit == 'true'": - problems.append(f"{where}: after the restore it only uploads, once, with `if: steps.native.outputs.hit == 'true'`") - problems += uploaded_as(where, cache, after[:1]) - lookup = first[1] - gate = f"needs.{lookup}.outputs.hit != 'true'" - for job in jobs: - if job != first and (lookup not in needs(parsed[job][1]) or not guarded(bare(job_key(parsed[job][1], "if")), gate)): - problems.append(f"{parsed[job][0]}: it builds {artifact}, so it needs {lookup} and its `if:` is " - f"{gate}, or that && more, with no ||") - lasts = [job for job in cached if job != first] - if len(lasts) != 1: - problems.append(f"{artifact}: one of the jobs that build it restores it under {lookup}'s key, to save it") - continue - last_where, last_outside, _, last_cache, _ = parsed[lasts[0]] - missing = sorted(j for _, j in jobs if (_, j) != lasts[0] and j not in needs(last_outside)) - if missing: - problems.append(f"{last_where}: it saves {artifact}, so it needs every job that builds a part: {', '.join(missing)}") - for name, want in (("key", f"${{{{needs.{lookup}.outputs.key}}}}"), ("artifact", field(cache, "artifact")), - ("path", field(cache, "path")), ("restore-only", "")): - if re.sub(r"\s", "", field(last_cache, name)) != re.sub(r"\s", "", want): - problems.append(f"{last_where}: its native-cache step's {name} must be {want or 'unset'}") - problems += restored(*parsed[lasts[0]], uploaded=lasts[0][0] == ni.BUILD_NATIVE) - if problems: - raise ni.Failure("\n ".join(["native-cache wiring:", *sorted(set(problems), key=problems.index)])) - - -STATUS = re.compile(r"\b(success|always|cancelled|failure)\s*\(", re.I) - - -def restored(where, outside, steps, cache, uploads, uploaded): - """The problems of a job that restores an output and builds it on a miss: it skips every step - but the upload on a hit, and when uploaded, uploads what it caches once, on a hit too.""" - problems = [] - for step in steps[steps.index(cache) + 1:]: - if step in uploads: - if bare(field(step, "if")): - problems.append(f"{where}: the upload must run on a hit too") - elif not guarded(bare(field(step, "if")), GUARD): - problems.append(f"{where}: `{step[0].strip()}` runs on a hit (its `if:` must be " - f"{GUARD}, or that && more, with no ||)") - if uploaded and len(uploads) != 1: - problems.append(f"{where}: it uploads what it restores once") - return problems + uploaded_as(where, cache, uploads) - - -def uploaded_as(where, cache, uploads): - """The problems of uploads that are not the cached output under its artifact's name (with the - leg's suffix in a matrix job).""" - problems = [] - for upload in uploads: - if field(upload, "path").rstrip("/") != field(cache, "path").rstrip("/"): - problems.append(f"{where}: uploads {field(upload, 'path')} but caches {field(cache, 'path')}") - if not re.sub(r"\s", "", field(upload, "name")).startswith(re.sub(r"\s", "", field(cache, "artifact"))): - problems.append(f"{where}: uploads {field(upload, 'name')}, not {field(cache, 'artifact')}") - return problems - - -def bare(condition): - return re.sub(r"^\$\{\{\s*|\s*\}\}$", "", " ".join(condition.split())) - - -def guarded(condition, guard): - """Whether an `if:` holds the guard, alone or && more, with no ||.""" - return re.match(rf"^{re.escape(guard)}\s*(&&|$)", condition) is not None and "||" not in condition - - -def job_key(outside, name): - """A job-level key's value; '' when the job has none. A value continued on plain lines is an - error, as in a step.""" - lines = sections(outside, 4, {name}) - return field(lines, name) if lines else "" - - -def needs(outside): - return {n.strip() for n in job_key(outside, "needs").strip("[]").split(",") if n.strip()} diff --git a/tools/tests/test_native_inputs.py b/tools/tests/test_native_inputs.py deleted file mode 100644 index a741876d7..000000000 --- a/tools/tests/test_native_inputs.py +++ /dev/null @@ -1,618 +0,0 @@ -#!/usr/bin/env python3 -"""Tests for tools/scripts/native-inputs.py (the keys) and tools/tests/check-native-inputs.py with its -parts in native_check (the check that holds the keys to what the jobs read). - -Owners: how OWNERS places a file. Commands, Yaml and Mentions: how the check reads workflow steps. -Each case is a way of running a file or make that, read wrong, would hide a read from the check. -Paths and Contexts: how the check finds the paths a file names and the values that change between -runs. - -Goals: what the keys must do, checked on throwaway commits of the working tree, and that the check -catches a job reading what its key leaves out. They need cargo (and make, for the jobs that run -it), so they are skipped without it; Static Checks has both. -""" -import importlib.util -import os -import re -import shutil -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -sys.dont_write_bytecode = True # no __pycache__ beside the scripts -HERE = os.path.dirname(os.path.abspath(__file__)) -spec = importlib.util.spec_from_file_location("check_native_inputs", os.path.join(HERE, "check-native-inputs.py")) -check = importlib.util.module_from_spec(spec) -spec.loader.exec_module(check) -from native_check import jobs, ni, paths, wiring # noqa: E402 (beside this file; after no-bytecode is set) - - -def step(*lines): - return [" - " + lines[0], *(" " + line for line in lines[1:])] - - -def ran(*lines): - _, files, guesses, make = jobs.commands(step(*lines), "test") - return files, [path for _, path in guesses], make - - -class Owners(unittest.TestCase): - def test_a_file_no_rule_places_is_read_by_every_artifact(self): - self.assertEqual(ni.owners("tools/helpers/new.sh"), ni.EVERYONE) - self.assertEqual(ni.owners("packages/canvas/src-native/new-platform/x.c"), ni.MOBILE) - - def test_the_last_matching_rule_decides(self): - self.assertEqual(ni.owners("packages/canvas/index.ts"), ni.NONE) - self.assertEqual(ni.owners("packages/canvas/src-native/canvas-ios/x.ts"), ("canvas-ios",)) - self.assertEqual(ni.owners("packages/canvas/platforms/ios/src/cpp/x.h"), ("canvas-android",)) - self.assertEqual(ni.owners("packages/canvas-media/platforms/linux/lib/x64/x.node"), ni.LINUX) - - def test_a_rule_matches_whole_path_segments(self): - self.assertTrue(ni.matches("tools/demo", "tools/demo/x.png")) - self.assertFalse(ni.matches("tools/demo", "tools/demos/x.png")) - self.assertTrue(ni.matches("packages/*/platforms", "packages/canvas/platforms/android/x.aar")) - - -class Commands(unittest.TestCase): - def test_interpreters_and_their_options(self): - self.assertEqual(ran("run: bash -e tools/scripts/x.sh")[0], {"tools/scripts/x.sh"}) - self.assertEqual(ran("run: bash -o pipefail tools/scripts/x.sh")[0], {"tools/scripts/x.sh"}) - self.assertEqual(ran("run: py -3 tools/x.py")[0], {"tools/x.py"}) - self.assertEqual(ran("run: pwsh -File tools\\scripts\\x.ps1")[0], {"tools/scripts/x.ps1"}) - self.assertEqual(ran("run: bash -c './tools/scripts/x.sh'")[0], {"tools/scripts/x.sh"}) - self.assertEqual(ran("run: bash -c 'echo hi'")[0], set()) - - def test_wrappers_and_their_options(self): - self.assertEqual(ran("run: sudo -E ./tools/x.sh")[0], {"tools/x.sh"}) - self.assertEqual(ran("run: timeout -s KILL 5m ./tools/x.sh")[0], {"tools/x.sh"}) - self.assertEqual(ran("run: env -u X FOO=1 ./tools/x.sh")[0], {"tools/x.sh"}) - self.assertEqual(ran("run: nice -n 10 make android")[2], (["android"], [])) - self.assertEqual(ran("run: arch -arm64 make ios")[2], (["ios"], [])) - for lines in (["run: sudo apt-get install -y make cmake"], ["run: command -v make"], ["run: which make"]): - with self.subTest(lines=lines): - self.assertEqual(ran(*lines)[2], None) - - def test_workspace_prefixes(self): - self.assertEqual(ran('run: bash "$GITHUB_WORKSPACE/tools/x.sh"')[0], {"tools/x.sh"}) - self.assertEqual(ran("run: ${{ github.workspace }}/tools/x.sh")[0], {"tools/x.sh"}) - - def test_working_directory_anywhere_in_the_step(self): - self.assertEqual(ran("working-directory: tools/scripts", "run: sh x.sh")[0], {"tools/scripts/x.sh"}) - self.assertEqual(ran("run: \"./x.sh\"", "working-directory: tools/scripts")[0], {"tools/scripts/x.sh"}) - - def test_paths_run_directly(self): - self.assertEqual(ran("run: ci/foo.sh")[0], {"ci/foo.sh"}) - self.assertEqual(ran("run: |", " bash \\", " ci/foo.sh")[0], {"ci/foo.sh"}) - self.assertEqual(ran("run: if true; then ./ci/foo.sh; fi")[0], {"ci/foo.sh"}) - - def test_quoting_escapes_heredocs_and_redirections(self): - self.assertEqual(ran("run: LLVM='C:\\Program Files\\LLVM' && echo \"a; b | c\"")[0], set()) - self.assertEqual(ran("run: bash \"tools/my scripts/x.sh\" 'a;b'")[0], {"tools/my scripts/x.sh"}) - self.assertEqual(ran("run: \"C:/Program Files/x/run.sh\"")[0], set()) - self.assertEqual(ran("run: |", " echo \"a \\\" b\"", " bash tools/x.sh")[0], {"tools/x.sh"}) - self.assertEqual(ran("run: |", " cat > f <<'EOF'", " it's", " EOF", " make android")[2], (["android"], [])) - self.assertEqual(ran("run: make android 2>&1 | tee build.log")[2], (["android"], [])) - - def test_a_script_without_extension_must_exist(self): - self.assertEqual(ran("working-directory: tools", "run: bash build")[1], ["tools/build"]) - - def test_refusals(self): - for lines in (["run: cd tools && ./x.sh"], ["run: python -m tools.x"], ["run: ./../x.sh"], - ["run: echo \"unclosed"], ["run: npm run build.canvas.ios"], ["run: |", " cat < tools/assets/icons/a.png', shell=True), set()) - self.assertEqual(named("cp tools/assets/icons/a.png out; echo tools/assets >> list", shell=True), - {"tools/assets/icons/a.png", "tools/assets"}) - - def test_shell_bare_names_exports_and_lists(self): - self.assertEqual(named("ls apps; tar czf x.tgz tools", shell=True), {"apps", "tools"}) - self.assertEqual(named('export ASSETS="$PWD/tools/assets"'), {"tools/assets"}) - self.assertEqual(named("set(SRC a.c tools/assets/icons/a.png)"), {"tools/assets/icons/a.png"}) - self.assertEqual(named("pushd tools; popd; pushd apps; cp demo/audio/a.wav /tmp/x", shell=True), {"apps/demo/audio/a.wav"}) - self.assertEqual(named("OTHER_CFLAGS = -I$(SRCROOT)/../../platforms/ios/src/cpp", "packages/canvas/src-native/android"), - {"packages/canvas/platforms/ios/src/cpp"}) - - def test_quoted_words_and_the_scripts_own_dir(self): - caches = "packages/canvas/platforms/ios/src/cpp/Caches.cpp" - self.assertIn(caches, named('cd "$(dirname "$0")/../packages/canvas/src-native/android"\n' - 'cp ../../platforms/ios/src/cpp/Caches.cpp x', "tools", shell=True)) - self.assertIn(caches, named('cd "$ROOT"/packages/canvas/src-native/android\ncat ../../platforms/ios/src/cpp/Caches.cpp', shell=True)) - self.assertIn("tools/assets", named('X="$ROOT"/tools/assets; cp -R "$X" out', shell=True)) - self.assertIn("tools/assets/icons/a.png", named('case $X in a) D=packages/canvas ;; b) D=tools ;; esac\n' - 'cd "$D"\ncat assets/icons/a.png', shell=True)) - - def test_a_default_a_dir_named_some_other_way_and_segments_over_lines(self): - self.assertIn("tools/assets/icons/a.png", named('F="${F:-$ROOT/tools/assets/icons/a.png}"\ngrep x "$F"', shell=True)) - self.assertEqual(named('let p = format!("{}/tools/assets/icons/a.png", root);'), {"tools/assets/icons/a.png"}) - self.assertEqual(named("const a = root + '/apps/demo/audio';"), {"apps/demo/audio"}) - self.assertEqual(named("const a = path.join(\n root,\n 'apps', 'demo', 'audio');"), {"apps/demo/audio"}) - - def test_a_value_set_is_read_where_a_command_is_given_it(self): - self.assertEqual(named("cat > cfg </dev/null 2>&1; then", - "git rev-parse --show-toplevel 2> /dev/null", "R=$(git rev-parse --show-toplevel)", - "git ls-files Cargo.toml", "git hash-object --stdin", "git diff --exit-code", - "git config --system core.longpaths true", "# the git mode of each entry"): - with self.subTest(line=line): - self.assertIsNone(wiring.reads_commit(line)) - - -IDENTITY = {f"GIT_{who}_{what}": value for who in ("AUTHOR", "COMMITTER") - for what, value in (("NAME", "native-inputs test"), ("EMAIL", "test@invalid"))} - - -def git(*args, env=None, data=None): - run = subprocess.run(["git", *args], input=data, capture_output=True, - env={**os.environ, **IDENTITY, **(env or {})}) - if run.returncode: - raise AssertionError(f"git {' '.join(args)}: {run.stderr.decode().strip()}") - return run.stdout.decode().strip() - - -@unittest.skipUnless(shutil.which("cargo"), "needs cargo") -class Goals(unittest.TestCase): - """The keys do what the change set out to: a TypeScript edit rebuilds nothing, a crate edit - every platform that links it, a Windows script edit only Windows, a Makefile edit every make - job, and a file nobody has placed everything. The check fails a job that reads what its key - leaves out. The base is HEAD with the working tree on top, untracked files too, so a local run - tests the change being made; CI's tree is clean.""" - - @classmethod - def setUpClass(cls): - cls.tmp = tempfile.TemporaryDirectory() - cls.index = {"GIT_INDEX_FILE": os.path.join(cls.tmp.name, "index")} - git("read-tree", "HEAD", env=cls.index) - git("add", "-A", env=cls.index) - cls.base = git("commit-tree", git("write-tree", env=cls.index), "-p", "HEAD", "-m", "test base", env=cls.index) - cls.keys = cls.all_keys(cls.base) - - @classmethod - def tearDownClass(cls): - cls.tmp.cleanup() - - @staticmethod - def all_keys(rev): - return {a: ni.key_inputs(a, rev) for a in ni.ARTIFACTS} - - def show(self, path): - return git("show", f"{self.base}:{path}") - - def commit(self, path, text, mode="100644", base=None): - base = base or self.base - git("read-tree", base, env=self.index) - blob = git("hash-object", "-w", "--stdin", data=text.encode()) - git("update-index", "--add", "--cacheinfo", f"{mode},{blob},{path}", env=self.index) - return git("commit-tree", git("write-tree", env=self.index), "-p", base, "-m", "probe", env=self.index) - - def moved(self, rev): - keys = self.all_keys(rev) - return {a for a in keys if keys[a] != self.keys[a]} - - def moved_by(self, path): - return self.moved(self.commit(path, self.show(path) + "\n# probe\n")) - - def edit(self, path, old, new): - text = self.show(path) - self.assertIn(old, text) - return self.commit(path, text.replace(old, new, 1)) - - def test_typescript(self): - self.assertEqual(self.moved_by("packages/canvas/index.ts"), set()) - - def test_crate(self): - moved = self.moved_by("crates/canvas-core/src/lib.rs") - self.assertLessEqual({"canvas-android", "canvas-ios", "canvas-windows", "linux", "unit-tests"}, moved) - self.assertFalse({"audio-context-android", "audio-context-ios"} & moved) - - def test_windows_script(self): - self.assertEqual(self.moved_by("tools/scripts/build-napi.sh"), set(ni.WINDOWS)) - - def test_makefile(self): - self.assertEqual(self.moved_by("Makefile"), set(ni.MAKE)) - - def test_a_new_file_nobody_placed(self): - self.assertEqual(self.moved(self.commit("tools/helpers/prep.sh", "echo prep\n")), set(ni.ARTIFACTS)) - - def test_a_scripts_mode(self): - path = "tools/scripts/build-napi.sh" - self.assertEqual(self.moved(self.commit(path, self.show(path), "100755")), set(ni.WINDOWS)) - - def test_a_requirement_in_any_member_moves_every_build_with_crates(self): - manifest = "crates/canvas-gamepad-napi/Cargo.toml" - pinned = self.edit(manifest, "[dependencies]", "[dependencies]\nlibc = \"=0.2.150\"") - self.assertEqual(self.moved(pinned), {a for a in ni.ARTIFACTS if ni.ARTIFACTS[a].get("crates")}) - self.assertFalse({"canvas-ios", "unit-tests"} & self.moved_by(manifest)) - - def test_a_patched_crate_keys_every_build_with_crates_also_as_a_member(self): - member = self.edit("Cargo.toml", "members = [", 'members = [\n "crates/vendor/cpal",') - device = "crates/vendor/cpal/src/host/wasapi/device.rs" - edited = self.commit(device, self.show(device) + "\n// probe\n", base=member) - for artifact in ("linux", "audio-context-windows"): - with self.subTest(artifact=artifact): - self.assertNotEqual(ni.key_inputs(artifact, member), ni.key_inputs(artifact, edited)) - - def test_a_key_from_another_dir(self): - script = os.path.join(HERE, "..", "scripts", "native-inputs.py") - out = subprocess.run([sys.executable, script, "audio-context-ios", self.base], cwd=HERE, capture_output=True, text=True) - self.assertEqual(out.returncode, 0, out.stderr) - - def test_a_local_action_named_another_way_is_refused(self): - rev = self.edit(ni.BUILD_NATIVE, " - uses: ./.github/actions/setup-android-native", - " - { uses: ./.github/actions/setup-android-native }") - self.assertRaises(ni.Failure, ni.key_inputs, "canvas-android", rev) - - def problems(self, artifact, rev): - return check.check_reads(artifact, rev) - - def test_check_fails_a_read_the_key_leaves_out(self): - rev = self.edit(ni.BUILD_NATIVE, "run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi", - "run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi && cat V8_RELEASE") - self.assertTrue(any("V8_RELEASE" in p for p in self.problems("canvas-windows", rev))) - - def test_check_fails_a_dir_a_script_copies(self): - script = "tools/scripts/build-napi.sh" - rev = self.commit(script, self.show(script) + '\ncp -R tools/assets/ "$DEST/"\n') - self.assertTrue(any("tools/assets" in p for p in self.problems("canvas-windows", rev))) - - def test_check_fails_a_read_after_a_quoted_cd(self): - script = "tools/scripts/build-napi.sh" - rev = self.commit(script, self.show(script) + '\ncd "$(dirname "$0")/../../packages/canvas-svg/src-native/ios"\n' - "cp ../../../canvas/src-native/canvas-ios/CanvasNative/include/canvas_ios.h x\n") - self.assertTrue(any("canvas_ios.h" in p for p in self.problems("canvas-windows", rev))) - - def test_check_fails_a_read_in_a_quoted_substitution(self): - script = "tools/scripts/build-napi.sh" - rev = self.commit(script, self.show(script) + '\nV8_TAG="$(cat "$REPO/V8_RELEASE")"\n') - self.assertTrue(any("V8_RELEASE" in p for p in self.problems("canvas-windows", rev))) - - def test_a_large_fixture_of_a_crates_tests_is_not_scanned(self): - rev = self.commit("crates/canvas-svg/tests/big.svg", "\n" * 300_000) - self.assertFalse(any("too large" in p for p in self.problems("canvas-svg-android", rev))) - - def test_check_fails_a_file_a_build_step_hashes(self): - workflow = ".github/workflows/build-native.yml" - text = self.show(workflow) - build = "run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi\n" - self.assertEqual(text.count(build), 1) - rev = self.commit(workflow, text.replace(build, build.replace("run: ", "run: echo ${{ hashFiles('V8_RELEASE') }} && "))) - self.assertTrue(any("V8_RELEASE" in p for p in self.problems("canvas-windows", rev))) - - def test_a_module_build_napi_writes_is_no_read(self): - script = "tools/scripts/build-napi.sh" - rev = self.commit(script, self.show(script).replace('echo "$DEST/$NAME.node"', 'ls -l "$DEST/$NAME.node"; du -sh "$DEST"')) - self.assertEqual(self.problems("canvas-windows", rev), []) - rev = self.commit(script, self.show(script) + '\ncp "$ROOT/packages/canvas/platforms/windows/THIRD_PARTY_NOTICES.txt" "$DEST/x"\n') - self.assertTrue(any("THIRD_PARTY_NOTICES" in p for p in self.problems("canvas-svg-windows", rev))) - - def test_check_fails_a_step_of_an_action_that_runs_after_a_failure(self): - action = ".github/actions/setup-windows-native/action.yml" - text = self.show(action) - at = text.index(" - name:", text.index("runs:")) - for key, needle in (("continue-on-error: true", "continue-on-error"), ("if: always()", "status function")): - with self.subTest(key=key): - rev = self.commit(action, text[:at] + f" - name: probe\n {key}\n shell: bash\n run: 'true'\n" + text[at:]) - self.assertTrue(any(needle in p for p in self.problems("canvas-windows", rev))) - - def test_check_fails_a_value_of_the_run(self): - script = "tools/scripts/build-napi.sh" - for line, needle in (('echo "$GITHUB_SHA" > stamp', "GITHUB_SHA"), ("git describe --tags > stamp", "commit")): - with self.subTest(line=line): - rev = self.commit(script, self.show(script) + f"\n{line}\n") - self.assertTrue(any(needle in p for p in self.problems("canvas-windows", rev))) - - def test_a_followed_script_is_held_to_the_refusals(self): - script = "tools/scripts/build-napi.sh" - for line in ("npx nx run canvas:build", "cargo build --workspace", "python3 -m gen", '[ -n "$X" ] && . "$DIR/$NAME.sh"'): - with self.subTest(line=line): - self.assertRaises(ni.Failure, self.problems, "canvas-windows", self.commit(script, self.show(script) + f"\n{line}\n")) - self.problems("canvas-windows", self.commit(script, self.show(script) + '\n[ -f "$HOME/.cargo/env" ] && . "$HOME/.cargo/env"\n')) - - def test_check_holds_the_claims_about_fixtures(self): - rule = "apps/demo/src/assets/file-assets/audio" - saved = list(ni.OWNERS) - ni.OWNERS[:] = [r for r in ni.OWNERS if r[0] != rule] - ni.owners.cache_clear() - try: - self.assertEqual(len(ni.OWNERS), len(saved) - 1) - self.assertTrue(any(rule in p for p in self.problems("canvas-windows", self.base))) - finally: - ni.OWNERS[:] = saved - ni.owners.cache_clear() - - @unittest.skipUnless(shutil.which("make"), "needs make") - def test_check_holds_the_claims_about_build_files(self): - rule = "packages/canvas/platforms/ios/src/cpp" - saved = list(ni.OWNERS) - ni.OWNERS[:] = [r for r in ni.OWNERS if r[0] != rule] - ni.owners.cache_clear() - try: - self.assertTrue(any(rule in p for p in self.problems("canvas-android", self.base))) - finally: - ni.OWNERS[:] = saved - ni.owners.cache_clear() - - def test_the_wiring(self): - guarded = " - name: Build Rust libraries\n if: steps.native.outputs.hit != 'true'\n run: make android" - for name, new in (("unguarded", " - name: Build Rust libraries\n run: make android"), - ("|| guard", guarded.replace("!= 'true'", "!= 'true' || always()")), - ("status function", guarded.replace("!= 'true'", "!= 'true' && !success()")), - ("status function in another case", guarded.replace("!= 'true'", "!= 'true' && Always()")), - ("continue-on-error", guarded + "\n continue-on-error: true"), - ("run context", guarded.replace("run: make android", "run: echo ${{ github.sha }} && make android"))): - with self.subTest(name=name): - self.assertRaises(ni.Failure, wiring.check_wiring, self.edit(ni.BUILD_NATIVE, guarded, new)) - upload = " - uses: actions/upload-artifact@v4\n with:\n name: canvas-android\n" - for name, new in (("renamed upload", upload.replace("name: canvas-android", "name: android")), ("no upload", "")): - with self.subTest(name=name): - self.assertRaises(ni.Failure, wiring.check_wiring, self.edit( - ni.BUILD_NATIVE, upload + " path: packages/canvas/platforms/android/canvas-release.aar\n" - " if-no-files-found: error\n", new and new + " path: packages/canvas/platforms/android/" - "canvas-release.aar\n if-no-files-found: error\n")) - self.assertRaises(ni.Failure, wiring.check_wiring, - self.edit(ni.BUILD_NATIVE, " variant: ${{ toJSON(matrix) }}\n", "")) - leg = " - name: canvas-gamepad\n crate: canvas-gamepad-napi\n file: canvasgamepad.node\n" - self.assertRaises(ni.Failure, wiring.check_wiring, self.edit(ni.BUILD_NATIVE, leg, leg + leg.replace("canvas-gamepad\n", "canvas-foo\n"))) - # GitHub evaluates expressions in an action's input descriptions and fails to load it. - self.assertRaises(ni.Failure, wiring.check_wiring, self.edit( - f"{ni.CACHE_ACTION}/action.yml", " description: The job's entry", " description: ${{ inputs.x }} The job's entry")) - wiring.check_wiring(self.base) - - def test_the_wiring_of_an_artifact_built_in_parts(self): - gate = " needs: canvas-ios-cache\n if: needs.canvas-ios-cache.outputs.hit != 'true'\n" - combine = " needs: [canvas-ios-cache, canvas-apple]\n if: needs.canvas-ios-cache.outputs.hit != 'true'\n" - for name, old, new in (("ungated part", gate, " needs: canvas-ios-cache\n"), - ("|| gate", gate, gate.replace("!= 'true'", "!= 'true' || always()")), - ("own key", " key: ${{ needs.canvas-ios-cache.outputs.key }}\n", ""), - ("saving first job", " artifact: canvas-ios\n path: canvas-ios.tar.gz\n" - " restore-only: 'true'\n", - " artifact: canvas-ios\n path: canvas-ios.tar.gz\n"), - ("first job uploading on a miss", " if: steps.native.outputs.hit == 'true'\n" - " with:\n name: canvas-ios\n", - " with:\n name: canvas-ios\n"), - ("last job running after a failed part", combine, - combine.replace("'true'\n", "'true' && !cancelled()\n")), - ("last job not needing the parts", combine, combine.replace(", canvas-apple]", "]")), - ("if: continued on the next line", combine, - combine.replace("'true'\n", "'true' &&\n always()\n"))): - with self.subTest(name=name): - self.assertRaises(ni.Failure, wiring.check_wiring, self.edit(ni.BUILD_NATIVE, old, new)) - self.assertIn(f"{ni.BUILD_NATIVE}#canvas-apple", ni.key_inputs("canvas-ios", self.base)) - - def test_check_fails_a_build_file_naming_a_crate_outside_the_closure(self): - rev = self.commit("packages/audio-context/src-native/android/extra.gradle", 'cargo { module = "../../../../crates/canvas-core" }\n') - self.assertTrue(any("crates/canvas-core" in p for p in self.problems("audio-context-android", rev))) - - def test_a_shared_job_reads_with_each_artifacts_own_matrix_values(self): - build = " run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi ${{ matrix.module.crate }}" - for line, flagged in (("cp -R packages/canvas-media/platforms/windows/x64/ x", True), - ("cp packages/canvas-media/platforms/windows/${{ matrix.arch }}/canvasmedia.node x", True), - ("cp -R packages/${{ matrix.module.name }}/platforms/windows/x64/ x", False)): - with self.subTest(line=line): - rev = self.edit(ni.BUILD_NATIVE, build, build.replace("run: ", f"run: {line} && ")) - self.assertEqual(any("canvas-media/platforms/windows" in p for p in self.problems("canvas-svg-windows", rev)), flagged) - - def test_an_output_without_crates_needs_no_cargo(self): - with mock.patch.object(ni, "crate_meta", side_effect=AssertionError("ran cargo")): - ni.key_inputs("audio-context-android", self.base) - - -if __name__ == "__main__": - sys.exit(unittest.main(verbosity=1)) From 53dd8537dce3e0a1be4f22034f13835bb98d1e82 Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:14:13 +0800 Subject: [PATCH 11/12] ci: reuse each native build's output until its inputs change Each native job lists what its output is built from as git pathspecs. The native-cache action hashes git's ids of those files, restores the output under that key and skips the build on a hit. This replaces the per-job hashFiles keys and adds the four outputs that had none: canvas-android, canvas-ios, canvas-windows and linux. A Linux lookup restores the split xcframeworks, so a hit takes no macOS runner. Releases (tags) always build. --- .github/actions/native-cache/action.yml | 57 +++++++ .github/workflows/build-native.yml | 199 ++++++++++++++++-------- 2 files changed, 195 insertions(+), 61 deletions(-) create mode 100644 .github/actions/native-cache/action.yml diff --git a/.github/actions/native-cache/action.yml b/.github/actions/native-cache/action.yml new file mode 100644 index 000000000..2c66d42e6 --- /dev/null +++ b/.github/actions/native-cache/action.yml @@ -0,0 +1,57 @@ +name: Native output cache +description: > + Restores a job's output when the files it is built from are unchanged, so the job can skip its + build; otherwise saves the output once the job succeeds. Releases (tags) always build. + +inputs: + name: + description: Cache entry; one per output (and matrix arch) + required: true + path: + description: The output, as the job uploads it + required: true + inputs: + description: > + Git pathspecs of what the output is built from. Each has to match a tracked file, so a + renamed input fails the job. `.github/actions` and build-native.yml always count. + required: true + restore-only: + description: "'true' when a later job builds and saves the output, under this action's `key`" + default: 'false' + +outputs: + cache-hit: + description: "'true' when the output was restored" + value: ${{ steps.cache.outputs.cache-hit || steps.restore.outputs.cache-hit }} + key: + description: The cache key + value: ${{ steps.key.outputs.key }} + +runs: + using: composite + steps: + # Git's hashes of the files, so every OS computes the same key. The week bounds how stale the + # crates.io versions and toolchains in a reused output can be. Bump v1 to drop every entry. + - id: key + shell: bash + env: + NAME: ${{ inputs.name }} + INPUTS: ${{ inputs.inputs }} + run: | + set -f + hash=$(git ls-files -s --error-unmatch -- .github/actions .github/workflows/build-native.yml $INPUTS | git hash-object --stdin) + echo "key=native-v1-$NAME-$(date -u +%G-W%V)-$hash" >> "$GITHUB_OUTPUT" + + - id: cache + if: github.ref_type != 'tag' && inputs.restore-only != 'true' + uses: actions/cache@v4 + with: + path: ${{ inputs.path }} + key: ${{ steps.key.outputs.key }} + + - id: restore + if: github.ref_type != 'tag' && inputs.restore-only == 'true' + uses: actions/cache/restore@v4 + with: + path: ${{ inputs.path }} + key: ${{ steps.key.outputs.key }} diff --git a/.github/workflows/build-native.yml b/.github/workflows/build-native.yml index 15255e57d..44a8be76b 100644 --- a/.github/workflows/build-native.yml +++ b/.github/workflows/build-native.yml @@ -42,10 +42,9 @@ # run the Node-API test suites on the shipped modules (on WARP: runners have no GPU; # audio renders offline and on the 'none' sink: they have no audio device either). # -# The napi-windows modules and the canvas-svg / audio-context mobile builds change rarely, so -# their jobs cache the final artifact keyed on a hash of their sources and skip the whole build -# on a hit. The other jobs that build Skia keep its built libraries per target in -# .github/actions/skia-cache, saved only by pushes to master. +# Each job restores its output from .github/actions/native-cache, and skips the build when the files +# it lists as `inputs` are unchanged. The jobs that build Skia also keep its built libraries per +# target in .github/actions/skia-cache, saved only by pushes to master. name: Build Native permissions: @@ -55,7 +54,7 @@ on: workflow_call: env: - # bump to invalidate the canvas-svg / audio-context / canvas-media artifact caches + # bump to invalidate the opus deps cache NATIVE_CACHE_VERSION: v1 jobs: @@ -64,25 +63,44 @@ jobs: runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 + - uses: ./.github/actions/native-cache + id: cache + with: + name: canvas-android + path: packages/canvas/platforms/android/canvas-release.aar + inputs: >- + Cargo.toml .cargo Makefile + crates :!crates/canvas-svg* :!crates/canvas-ios :!crates/*-napi/* + V8_RELEASE NATIVESCRIPT_IOS_RUNTIME_REF tools/scripts/download-v8.sh + tools/scripts/build-android-v8-stub.sh tools/scripts/build-android.sh + packages/canvas/src-native/canvas-android packages/canvas/platforms/ios/src/cpp - uses: ./.github/actions/setup-android-native + if: steps.cache.outputs.cache-hit != 'true' - uses: ./.github/actions/skia-cache + if: steps.cache.outputs.cache-hit != 'true' with: name: canvas-android - name: Fetch V8 + NativeScript runtime headers + if: steps.cache.outputs.cache-hit != 'true' run: ./tools/scripts/download-v8.sh - name: Build libNativeScript.so stub for linking + if: steps.cache.outputs.cache-hit != 'true' run: ./tools/scripts/build-android-v8-stub.sh - name: Build Rust libraries + if: steps.cache.outputs.cache-hit != 'true' run: make android # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache + if: steps.cache.outputs.cache-hit != 'true' with: name: canvas-android save: 'true' - name: Build canvas AAR + if: steps.cache.outputs.cache-hit != 'true' working-directory: packages/canvas/src-native/canvas-android run: ./gradlew :canvas:assembleRelease - name: Copy AAR into platforms/android + if: steps.cache.outputs.cache-hit != 'true' run: cp packages/canvas/src-native/canvas-android/canvas/build/outputs/aar/canvas-release.aar packages/canvas/platforms/android/canvas-release.aar - uses: actions/upload-artifact@v4 with: @@ -90,10 +108,56 @@ jobs: path: packages/canvas/platforms/android/canvas-release.aar if-no-files-found: error + # The xcframeworks built by several jobs: a hit uploads one here, on Linux, and its macOS jobs never + # start. On a miss the last of them saves it under this job's key. + apple-cache: + name: Apple xcframeworks (cached) + runs-on: ubuntu-22.04 + outputs: + canvas-hit: ${{ steps.canvas.outputs.cache-hit }} + canvas-key: ${{ steps.canvas.outputs.key }} + svg-hit: ${{ steps.svg.outputs.cache-hit }} + svg-key: ${{ steps.svg.outputs.key }} + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/native-cache + id: canvas + with: + name: canvas-ios + path: canvas-ios.tar.gz + restore-only: 'true' + inputs: >- + Cargo.toml .cargo Makefile + crates :!crates/canvas-svg* :!crates/canvas-android :!crates/*-napi/* + V8_RELEASE NATIVESCRIPT_IOS_RUNTIME_REF tools/scripts/download-v8.sh + tools/scripts/canvas-build.sh packages/canvas/src-native/canvas-ios + - uses: actions/upload-artifact@v4 + if: steps.canvas.outputs.cache-hit == 'true' + with: + name: canvas-ios + path: canvas-ios.tar.gz + - uses: ./.github/actions/native-cache + id: svg + with: + name: canvas-svg-ios + path: canvas-svg-ios.tar.gz + restore-only: 'true' + inputs: >- + Cargo.toml .cargo Makefile + crates :!crates/canvas-2d :!crates/canvas-c :!crates/canvas-webgl :!crates/canvas-android :!crates/canvas-ios :!crates/*-napi/* :!crates/canvas-svg-android + tools/scripts/canvas-svg-build.sh packages/canvas-svg/src-native/ios + - uses: actions/upload-artifact@v4 + if: steps.svg.outputs.cache-hit == 'true' + with: + name: canvas-svg-ios + path: canvas-svg-ios.tar.gz + # One runner per platform: its Rust targets, then its framework slices. The Xcode pre-build # phase reruns cargo for each slice, so the slices are built in the job that owns the target dir. canvas-apple: name: Canvas ${{ matrix.platform }} + needs: apple-cache + if: needs.apple-cache.outputs.canvas-hit != 'true' runs-on: macos-15 strategy: fail-fast: false @@ -130,7 +194,7 @@ jobs: canvas-ios: name: Canvas xcframework - needs: canvas-apple + needs: [apple-cache, canvas-apple] runs-on: macos-15 steps: - uses: actions/checkout@v4 @@ -151,6 +215,11 @@ jobs: run: sh canvas-build.sh --xcframework - name: Pack xcframework run: tar -czf canvas-ios.tar.gz -C packages/canvas/platforms/ios/CanvasNativeBinary CanvasNative.xcframework + - uses: actions/cache/save@v4 + if: github.ref_type != 'tag' + with: + path: canvas-ios.tar.gz + key: ${{ needs.apple-cache.outputs.canvas-key }} - uses: actions/upload-artifact@v4 with: name: canvas-ios @@ -162,12 +231,19 @@ jobs: runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 - - name: Restore cached AAR + - uses: ./.github/actions/native-cache id: svg-aar - uses: actions/cache@v4 with: + name: canvas-svg-android path: packages/canvas-svg/platforms/android/canvassvg-release.aar - key: ${{ env.NATIVE_CACHE_VERSION }}-canvas-svg-android-${{ hashFiles('crates/canvas-svg/**', 'crates/canvas-svg-c/**', 'crates/canvas-svg-android/**', 'crates/canvas-utils/**', 'crates/canvas-core/**', 'crates/gl-bindings/**', 'packages/canvas-svg/src-native/android/**', '!packages/canvas-svg/src-native/android/**/build/**', '!packages/canvas-svg/src-native/android/**/jniLibs/**', 'Cargo.lock', 'tools/scripts/build-svg-android.sh', 'tools/scripts/copy-svg-android.sh', 'Makefile') }} + inputs: >- + Cargo.toml .cargo Makefile + crates :!crates/canvas-2d :!crates/canvas-c :!crates/canvas-webgl :!crates/canvas-android :!crates/canvas-ios :!crates/*-napi/* :!crates/canvas-svg-ios + V8_RELEASE NATIVESCRIPT_IOS_RUNTIME_REF tools/scripts/download-v8.sh + tools/scripts/build-android-v8-stub.sh + tools/scripts/build-svg-android.sh tools/scripts/copy-svg-android.sh + packages/canvas-svg/src-native/android packages/canvas-svg/platforms/ios/src/cpp + packages/canvas/src-native/canvas-android/canvas/src/main/cpp - uses: ./.github/actions/setup-android-native if: steps.svg-aar.outputs.cache-hit != 'true' - uses: ./.github/actions/skia-cache @@ -206,29 +282,10 @@ jobs: path: packages/canvas-svg/platforms/android/canvassvg-release.aar if-no-files-found: error - # canvas-svg changes rarely: on a hit for its xcframework the per-platform jobs never start. - # The lookup runs on macOS like the restore, so both compute the same cache version. - canvas-svg-cache: - name: Canvas SVG cache lookup - runs-on: macos-15 - outputs: - key: ${{ steps.key.outputs.key }} - hit: ${{ steps.lookup.outputs.cache-hit }} - steps: - - uses: actions/checkout@v4 - - id: key - run: echo "key=${{ env.NATIVE_CACHE_VERSION }}-canvas-svg-ios-${{ hashFiles('crates/canvas-svg/**', 'crates/canvas-svg-c/**', 'crates/canvas-svg-ios/**', 'crates/canvas-utils/**', 'crates/canvas-core/**', 'packages/canvas-svg/src-native/ios/**', '!packages/canvas-svg/src-native/ios/dist/**', 'Cargo.lock', 'tools/scripts/canvas-svg-build.sh', 'Makefile') }}" >> "$GITHUB_OUTPUT" - - id: lookup - uses: actions/cache/restore@v4 - with: - path: canvas-svg-ios.tar.gz - key: ${{ steps.key.outputs.key }} - lookup-only: true - canvas-svg-apple: name: Canvas SVG ${{ matrix.platform }} - needs: canvas-svg-cache - if: needs.canvas-svg-cache.outputs.hit != 'true' + needs: apple-cache + if: needs.apple-cache.outputs.svg-hit != 'true' runs-on: macos-15 strategy: fail-fast: false @@ -262,39 +319,32 @@ jobs: canvas-svg-ios: name: Canvas SVG xcframework - needs: [canvas-svg-cache, canvas-svg-apple] - if: ${{ !cancelled() && needs.canvas-svg-cache.result == 'success' && contains(fromJSON('["success","skipped"]'), needs.canvas-svg-apple.result) }} + needs: [apple-cache, canvas-svg-apple] runs-on: macos-15 steps: - uses: actions/checkout@v4 - - name: Restore cached xcframework - id: svg-xcframework - uses: actions/cache@v4 - with: - path: canvas-svg-ios.tar.gz - key: ${{ needs.canvas-svg-cache.outputs.key }} - uses: maxim-lobanov/setup-xcode@v1 - if: steps.svg-xcframework.outputs.cache-hit != 'true' with: xcode-version: '^16.0' - uses: actions/download-artifact@v4 - if: steps.svg-xcframework.outputs.cache-hit != 'true' with: pattern: canvas-svg-apple-* merge-multiple: true path: slices - name: Unpack slices - if: steps.svg-xcframework.outputs.cache-hit != 'true' run: | mkdir -p packages/canvas-svg/src-native/ios/dist for f in slices/*.tar.gz; do tar -xzf "$f" -C packages/canvas-svg/src-native/ios/dist; done - name: Build CanvasSVG.xcframework - if: steps.svg-xcframework.outputs.cache-hit != 'true' working-directory: tools/scripts run: sh canvas-svg-build.sh --xcframework - name: Pack xcframework - if: steps.svg-xcframework.outputs.cache-hit != 'true' run: tar -czf canvas-svg-ios.tar.gz -C packages/canvas-svg/platforms/ios/CanvasSVGBinary CanvasSVG.xcframework + - uses: actions/cache/save@v4 + if: github.ref_type != 'tag' + with: + path: canvas-svg-ios.tar.gz + key: ${{ needs.apple-cache.outputs.svg-key }} - uses: actions/upload-artifact@v4 with: name: canvas-svg-ios @@ -309,12 +359,13 @@ jobs: with: # Oboe submodules: true - - name: Restore cached AAR + - uses: ./.github/actions/native-cache id: audio-aar - uses: actions/cache@v4 with: + name: audio-context-android path: packages/audio-context/platforms/android/audiocontext-release.aar - key: ${{ env.NATIVE_CACHE_VERSION }}-audio-context-android-${{ hashFiles('packages/audio-context/src-native/android/**', '!packages/audio-context/src-native/android/**/build/**') }} + inputs: >- + packages/audio-context/src-native/android - uses: actions/setup-java@v4 if: steps.audio-aar.outputs.cache-hit != 'true' with: @@ -344,12 +395,13 @@ jobs: runs-on: macos-15 steps: - uses: actions/checkout@v4 - - name: Restore cached xcframework + - uses: ./.github/actions/native-cache id: audio-xcframework - uses: actions/cache@v4 with: + name: audio-context-ios path: audio-context-ios.tar.gz - key: ${{ env.NATIVE_CACHE_VERSION }}-audio-context-ios-${{ hashFiles('packages/audio-context/src-native/ios/**', 'tools/scripts/audio-context-build.sh') }} + inputs: >- + packages/audio-context/src-native/ios tools/scripts/audio-context-build.sh - uses: ./.github/actions/setup-apple-native if: steps.audio-xcframework.outputs.cache-hit != 'true' with: @@ -400,26 +452,41 @@ jobs: shell: bash steps: - uses: actions/checkout@v4 + - uses: ./.github/actions/native-cache + id: cache + with: + name: canvas-windows-${{ matrix.arch }} + path: packages/canvas/platforms/windows/${{ matrix.arch }}/ + inputs: >- + Cargo.toml .cargo + crates :!crates/canvas-svg* :!crates/canvas-android :!crates/canvas-ios + :!crates/audio-context-napi :!crates/canvas-media-napi :!crates/canvas-gamepad-napi + tools/scripts/build-napi.sh tools/scripts/download-angle.sh - uses: ./.github/actions/setup-windows-native + if: steps.cache.outputs.cache-hit != 'true' with: target: ${{ matrix.target }} - uses: ./.github/actions/skia-cache + if: steps.cache.outputs.cache-hit != 'true' with: name: canvas-windows-${{ matrix.arch }} - uses: actions/setup-node@v4 + if: steps.cache.outputs.cache-hit != 'true' with: node-version: '22' - name: Build canvasnative.node (and fetch ANGLE) + if: steps.cache.outputs.cache-hit != 'true' run: ./tools/scripts/build-napi.sh ${{ matrix.target }} release-napi # arm64 is cross-compiled, so only x64 runs them. The runners have no GPU: D3D12 and ANGLE # fall back to WARP, and the WebGPU suites skip without an adapter. # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache + if: steps.cache.outputs.cache-hit != 'true' with: name: canvas-windows-${{ matrix.arch }} save: 'true' - name: Node-API tests - if: matrix.arch == 'x64' + if: steps.cache.outputs.cache-hit != 'true' && matrix.arch == 'x64' env: CANVAS_NAPI_ADDON: ${{ github.workspace }}\packages\canvas\platforms\windows\x64\canvasnative.node run: node --expose-gc --test "crates/canvas-napi/__test__/*.test.mjs" @@ -437,12 +504,12 @@ jobs: fail-fast: false matrix: module: - # `sources`: every tracked directory the module is built from (its cache key). + # `sources`: every crate the module is built from (its cache key). - name: canvas-svg crate: canvas-svg-napi file: canvassvg.node addon-env: CANVAS_SVG_NAPI_ADDON - sources: crates/canvas-svg crates/canvas-svg-c crates/canvas-svg-napi crates/canvas-utils + sources: crates/canvas-svg crates/canvas-svg-c crates/canvas-svg-napi crates/canvas-utils crates/canvas-core crates/gl-bindings skia: true # Runners have no audio device: its suite renders offline and on the 'none' sink. - name: audio-context @@ -473,18 +540,13 @@ jobs: MODULE_DIR: packages/${{ matrix.module.name }}/platforms/windows/${{ matrix.arch }} steps: - uses: actions/checkout@v4 - # The tree hashes of what the module is built from: equal hashes, equal module. - - name: Source key - id: sources - run: | - key=$(for path in ${{ matrix.module.sources }} crates/vendor/napi-sys Cargo.toml tools/scripts/build-napi.sh; do git rev-parse "HEAD:$path" || exit 1; done | sha256sum | cut -c1-32) - echo "key=$key" >> "$GITHUB_OUTPUT" - - name: Restore cached module + - uses: ./.github/actions/native-cache id: cache - uses: actions/cache@v4 with: + name: ${{ matrix.module.name }}-windows-${{ matrix.arch }} path: ${{ env.MODULE_DIR }}/${{ matrix.module.file }} - key: ${{ env.NATIVE_CACHE_VERSION }}-${{ matrix.module.name }}-windows-${{ matrix.arch }}-${{ steps.sources.outputs.key }} + inputs: >- + Cargo.toml .cargo crates/vendor tools/scripts/build-napi.sh ${{ matrix.module.sources }} - uses: ./.github/actions/setup-windows-native if: steps.cache.outputs.cache-hit != 'true' with: @@ -535,23 +597,38 @@ jobs: runner: ubuntu-22.04-arm steps: - uses: actions/checkout@v4 + - uses: ./.github/actions/native-cache + id: cache + with: + name: linux-${{ matrix.arch }} + path: packages/*/platforms/linux/lib/${{ matrix.arch }}/ + inputs: >- + Cargo.toml .cargo + crates :!crates/canvas-android :!crates/canvas-ios :!crates/canvas-svg-android :!crates/canvas-svg-ios + tools/scripts/build-linux.sh - uses: ./.github/actions/setup-linux-native + if: steps.cache.outputs.cache-hit != 'true' - uses: ./.github/actions/skia-cache + if: steps.cache.outputs.cache-hit != 'true' with: name: linux-${{ matrix.arch }} - uses: actions/setup-node@v4 + if: steps.cache.outputs.cache-hit != 'true' with: node-version: '22' - name: Build the Node-API modules + if: steps.cache.outputs.cache-hit != 'true' run: ./tools/scripts/build-linux.sh # Mesa's surfaceless EGL (llvmpipe) for 2D / WebGL and lavapipe for WebGPU: no GPU here. # canvas-media's suite drives Media Foundation, so it is Windows only. # Saved right after the Rust build, so a later failing step cannot drop the cache. - uses: ./.github/actions/skia-cache + if: steps.cache.outputs.cache-hit != 'true' with: name: linux-${{ matrix.arch }} save: 'true' - name: Node-API tests + if: steps.cache.outputs.cache-hit != 'true' env: CANVAS_NAPI_ADDON: ${{ github.workspace }}/packages/canvas/platforms/linux/lib/${{ matrix.arch }}/canvasnative.node CANVAS_SVG_NAPI_ADDON: ${{ github.workspace }}/packages/canvas-svg/platforms/linux/lib/${{ matrix.arch }}/canvassvg.node From f68df0c70b7cee5a15eebc08a16ce09adedb9728 Mon Sep 17 00:00:00 2001 From: Dylan Llewellyn <46717769+herefishyfish@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:50:21 +0800 Subject: [PATCH 12/12] ci: run again with no change to confirm the native outputs restore