diff --git a/.github/actions/fetch-tool/action.yml b/.github/actions/fetch-tool/action.yml new file mode 100644 index 0000000..8eb89ed --- /dev/null +++ b/.github/actions/fetch-tool/action.yml @@ -0,0 +1,78 @@ +name: Fetch a pinned tool +description: >- + Restores the tool's release file from the cache, or downloads it; checks its SHA-256 either way + (a cached copy that fails is downloaded again); installs it on PATH for the job's later steps; and + saves a new download to the cache at once, so a later failing step does not lose it. The caller + names the release URL and its SHA-256, so the pinned version stays visible in the workflow. Needs + the checkout and Node from .nvmrc (scripts/fetch-tool.ts runs with Node's TypeScript support). + +inputs: + name: + description: The file name the tool is installed under (a command name, or a jar's name). + required: true + url: + description: The release asset to download (a zip, a tar archive in any compression tar detects, or the tool itself). + required: true + sha256: + description: The SHA-256 of the downloaded file, from the official release. + required: true + archive-path: + description: The tool's path inside the archive; empty when the download is the tool itself. + required: false + default: '' + +outputs: + path: + description: The installed file, for tools run by path (a jar). + value: ${{ steps.fetch.outputs.path }} + downloaded: + description: "'true' when the file was downloaded (no cache entry, or a corrupted one), else 'false'." + value: ${{ steps.fetch.outputs.downloaded }} + +runs: + using: composite + steps: + # The cache entry is named after the URL and the checksum together. A version bump that changes + # the URL but not the pinned checksum misses the cache, so the new file is downloaded and fails + # its check, instead of the old file being restored and passing it. + - name: Cache entry for ${{ inputs.name }} + id: entry + shell: bash + env: + NAME: ${{ inputs.name }} + URL: ${{ inputs.url }} + SHA256: ${{ inputs.sha256 }} + run: >- + node -e 'const id = require("node:crypto").createHash("sha256") + .update(process.env.URL + "\n" + process.env.SHA256).digest("hex").slice(0, 32); + console.log("id=" + process.env.NAME + "-" + id)' >> "$GITHUB_OUTPUT" + + # An entry only ever holds a file that passed the check (it is saved below only after it). + - name: Restore cached ${{ inputs.name }} + id: restore + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/ci-tools-cache/${{ steps.entry.outputs.id }} + key: ci-tools-${{ runner.os }}-${{ steps.entry.outputs.id }} + + - name: Download, verify and install ${{ inputs.name }} + id: fetch + shell: bash + env: + NAME: ${{ inputs.name }} + URL: ${{ inputs.url }} + SHA256: ${{ inputs.sha256 }} + ARCHIVE_PATH: ${{ inputs.archive-path }} + CACHE_FILE: ${{ runner.temp }}/ci-tools-cache/${{ steps.entry.outputs.id }} + CACHE_KEY: ci-tools-${{ runner.os }}-${{ steps.entry.outputs.id }} + run: node scripts/fetch-tool.ts + + # A cache entry cannot be overwritten, and one that is restored on every run never expires. + # After a corrupted hit (downloaded again above, with a warning naming the key) every run + # downloads until someone deletes the entry with `gh cache delete `. + - name: Save ${{ inputs.name }} to the cache + if: steps.restore.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/ci-tools-cache/${{ steps.entry.outputs.id }} + key: ci-tools-${{ runner.os }}-${{ steps.entry.outputs.id }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9c5f69c..15ee83e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,10 +23,9 @@ jobs: lint: runs-on: ubuntu-latest - # Downloaded linters: one place for each version and the sha256 of its release file. The - # files are cached under these values, and every run checks the checksum, cached or not. + # Downloaded linters: one place for each version and the sha256 of its release file. Each is + # cached under its checksum and checked on every run, cached or not (.github/actions/fetch-tool). env: - TOOLS_DIR: /home/runner/.cache/ci-tools KTLINT_VERSION: 1.8.0 KTLINT_SHA256: a3fd620207d5c40da6ca789b95e7f823c54e854b7fade7f613e91096a3706d75 DETEKT_VERSION: 1.23.8 @@ -36,149 +35,125 @@ jobs: SWIFTLINT_VERSION: 0.65.1 SWIFTLINT_SHA256: caeed6f4a679c35539ffaf124f6c4ab4a8416917f7d8796279dc52b74026059d + # The tools are fetched first, so a download saved to the cache is kept whatever fails later. + # The JDK, every fetch and every check run even when an earlier step failed (`!cancelled()`), + # so one run reports every failing check; a check skips only when what it needs did not + # install (the yarn dependencies, the JDK or its tool). steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup + id: setup uses: ./.github/actions/setup - name: Install JDK (ktlint, detekt) + id: jdk + if: ${{ !cancelled() }} uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: 'zulu' java-version: '17' - # One cache per tool, keyed by its checksum: bumping one tool re-downloads only that one. Each - # is saved even when a later step fails (a lint finding is the common failure), and only a - # file that passed its checksum is ever written to the cached path. - - name: Restore cached ktlint - id: cache-ktlint - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + - name: Fetch ktlint + id: ktlint + if: ${{ !cancelled() }} + uses: ./.github/actions/fetch-tool with: - path: ${{ env.TOOLS_DIR }}/ktlint-${{ env.KTLINT_VERSION }} - key: ci-tools-${{ runner.os }}-ktlint-${{ env.KTLINT_SHA256 }} - - - name: Restore cached detekt - id: cache-detekt - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + name: ktlint + url: https://github.com/pinterest/ktlint/releases/download/${{ env.KTLINT_VERSION }}/ktlint + sha256: ${{ env.KTLINT_SHA256 }} + + - name: Fetch detekt + # Maven Central's artifact and the sha256 Central publishes for it. + id: detekt + if: ${{ !cancelled() }} + uses: ./.github/actions/fetch-tool with: - path: ${{ env.TOOLS_DIR }}/detekt-cli-${{ env.DETEKT_VERSION }}-all.jar - key: ci-tools-${{ runner.os }}-detekt-${{ env.DETEKT_SHA256 }} - - - name: Restore cached SwiftFormat - id: cache-swiftformat - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + name: detekt-cli.jar + url: https://repo1.maven.org/maven2/io/gitlab/arturbosch/detekt/detekt-cli/${{ env.DETEKT_VERSION }}/detekt-cli-${{ env.DETEKT_VERSION }}-all.jar + sha256: ${{ env.DETEKT_SHA256 }} + + - name: Fetch SwiftFormat + id: swiftformat + if: ${{ !cancelled() }} + uses: ./.github/actions/fetch-tool with: - path: ${{ env.TOOLS_DIR }}/swiftformat-${{ env.SWIFTFORMAT_VERSION }}-linux.zip - key: ci-tools-${{ runner.os }}-swiftformat-${{ env.SWIFTFORMAT_SHA256 }} - - - name: Restore cached SwiftLint - id: cache-swiftlint - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + name: swiftformat + url: https://github.com/nicklockwood/SwiftFormat/releases/download/${{ env.SWIFTFORMAT_VERSION }}/swiftformat_linux.zip + sha256: ${{ env.SWIFTFORMAT_SHA256 }} + archive-path: swiftformat_linux + + - name: Fetch SwiftLint + # The statically linked Linux build runs on this runner without a Swift toolchain. + id: swiftlint + if: ${{ !cancelled() }} + uses: ./.github/actions/fetch-tool with: - path: ${{ env.TOOLS_DIR }}/swiftlint-${{ env.SWIFTLINT_VERSION }}-linux-amd64.zip - key: ci-tools-${{ runner.os }}-swiftlint-${{ env.SWIFTLINT_SHA256 }} + name: swiftlint + url: https://github.com/realm/SwiftLint/releases/download/${{ env.SWIFTLINT_VERSION }}/swiftlint_linux_amd64.zip + sha256: ${{ env.SWIFTLINT_SHA256 }} + archive-path: swiftlint-static - name: Lint files + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn lint - name: Typecheck files + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn typecheck - name: Unused files, exports and dependencies (knip) + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn knip - name: Native contract is generated from the Codegen spec + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn contract --check - name: Expo demo dependencies match its Expo SDK (expo install --check, offline) # Offline: checks against the SDK's own bundledNativeModules.json, so the result changes only # with a change here. Online it would ask Expo's API for the newest patch releases, which can # be younger than .yarnrc.yml's 7-day npmMinimalAgeGate and so not installable yet. + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} env: EXPO_OFFLINE: '1' run: yarn workspace react-native-remote-compose-example-expo expo install --check - name: Unit tests (library contract, diagnostics, Expo plugin) + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn test --ci - - name: Script tests (native contract, measurement parsing, version copies) + - name: Script tests (native contract, measurement parsing, version copies, downloads) + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: yarn test:scripts - - name: Lint Kotlin (ktlint, checksum-pinned) - run: | - mkdir -p "$TOOLS_DIR" - tool="$TOOLS_DIR/ktlint-$KTLINT_VERSION" - [ -f "$tool" ] || { curl -sSfL -o "$tool.part" "https://github.com/pinterest/ktlint/releases/download/$KTLINT_VERSION/ktlint" && echo "$KTLINT_SHA256 $tool.part" | sha256sum -c - && mv "$tool.part" "$tool"; } - echo "$KTLINT_SHA256 $tool" | sha256sum -c - - chmod +x "$tool" - "$tool" "android/src/**/*.kt" "!android/src/main/java/com/remotecompose/contract/**" "tools/remote-compose-json/**/*.kt" "tools/remote-compose-json/*.kts" - - - name: Static analysis for Kotlin (detekt, checksum-pinned, new findings only) - # Maven Central's artifact and the sha256 Central publishes for it. Pre-existing findings - # are in detekt-baseline.xml. - run: | - mkdir -p "$TOOLS_DIR" - tool="$TOOLS_DIR/detekt-cli-$DETEKT_VERSION-all.jar" - [ -f "$tool" ] || { curl -sSfL -o "$tool.part" "https://repo1.maven.org/maven2/io/gitlab/arturbosch/detekt/detekt-cli/$DETEKT_VERSION/detekt-cli-$DETEKT_VERSION-all.jar" && echo "$DETEKT_SHA256 $tool.part" | sha256sum -c - && mv "$tool.part" "$tool"; } - echo "$DETEKT_SHA256 $tool" | sha256sum -c - - java -jar "$tool" --build-upon-default-config --config detekt.yml --baseline detekt-baseline.xml --input android/src,tools/remote-compose-json/src --excludes '**/contract/**' + - name: Lint Kotlin (ktlint) + if: ${{ !cancelled() && steps.jdk.outcome == 'success' && steps.ktlint.outcome == 'success' }} + run: ktlint "android/src/**/*.kt" "!android/src/main/java/com/remotecompose/contract/**" "tools/remote-compose-json/**/*.kt" "tools/remote-compose-json/*.kts" - - name: Format Swift (SwiftFormat --lint, checksum-pinned) - # The formatter lefthook runs before each commit, so a commit made without hooks is caught too. - run: | - mkdir -p "$TOOLS_DIR" - archive="$TOOLS_DIR/swiftformat-$SWIFTFORMAT_VERSION-linux.zip" - [ -f "$archive" ] || { curl -sSfL -o "$archive.part" "https://github.com/nicklockwood/SwiftFormat/releases/download/$SWIFTFORMAT_VERSION/swiftformat_linux.zip" && echo "$SWIFTFORMAT_SHA256 $archive.part" | sha256sum -c - && mv "$archive.part" "$archive"; } - echo "$SWIFTFORMAT_SHA256 $archive" | sha256sum -c - - unzip -q -o "$archive" -d "$RUNNER_TEMP/swiftformat" - "$RUNNER_TEMP/swiftformat/swiftformat_linux" --lint ios - - - name: Lint Swift (SwiftLint, checksum-pinned) - # The statically linked Linux build runs on this runner without a Swift toolchain. It skips - # the few rules that need SourceKit (statement_position; SwiftFormat covers that one). - run: | - mkdir -p "$TOOLS_DIR" - archive="$TOOLS_DIR/swiftlint-$SWIFTLINT_VERSION-linux-amd64.zip" - [ -f "$archive" ] || { curl -sSfL -o "$archive.part" "https://github.com/realm/SwiftLint/releases/download/$SWIFTLINT_VERSION/swiftlint_linux_amd64.zip" && echo "$SWIFTLINT_SHA256 $archive.part" | sha256sum -c - && mv "$archive.part" "$archive"; } - echo "$SWIFTLINT_SHA256 $archive" | sha256sum -c - - unzip -q -o "$archive" -d "$RUNNER_TEMP/swiftlint" - "$RUNNER_TEMP/swiftlint/swiftlint-static" lint --strict --no-cache - - - name: Save downloaded ktlint to the cache - if: always() && steps.cache-ktlint.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ env.TOOLS_DIR }}/ktlint-${{ env.KTLINT_VERSION }} - key: ci-tools-${{ runner.os }}-ktlint-${{ env.KTLINT_SHA256 }} - - - name: Save downloaded detekt to the cache - if: always() && steps.cache-detekt.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ env.TOOLS_DIR }}/detekt-cli-${{ env.DETEKT_VERSION }}-all.jar - key: ci-tools-${{ runner.os }}-detekt-${{ env.DETEKT_SHA256 }} + - name: Static analysis for Kotlin (detekt) + # No baseline: a finding is fixed or suppressed where it is, with the reason. + if: ${{ !cancelled() && steps.jdk.outcome == 'success' && steps.detekt.outcome == 'success' }} + env: + DETEKT_JAR: ${{ steps.detekt.outputs.path }} + run: java -jar "$DETEKT_JAR" --build-upon-default-config --config detekt.yml --input android/src,tools/remote-compose-json/src --excludes '**/contract/**' - - name: Save downloaded SwiftFormat to the cache - if: always() && steps.cache-swiftformat.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ env.TOOLS_DIR }}/swiftformat-${{ env.SWIFTFORMAT_VERSION }}-linux.zip - key: ci-tools-${{ runner.os }}-swiftformat-${{ env.SWIFTFORMAT_SHA256 }} + - name: Format Swift (SwiftFormat --lint) + # The formatter lefthook runs before each commit, so a commit made without hooks is caught too. + if: ${{ !cancelled() && steps.swiftformat.outcome == 'success' }} + run: swiftformat --lint ios - - name: Save downloaded SwiftLint to the cache - if: always() && steps.cache-swiftlint.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: ${{ env.TOOLS_DIR }}/swiftlint-${{ env.SWIFTLINT_VERSION }}-linux-amd64.zip - key: ci-tools-${{ runner.os }}-swiftlint-${{ env.SWIFTLINT_SHA256 }} + - name: Lint Swift (SwiftLint) + # The static build skips the few rules that need SourceKit (statement_position; SwiftFormat + # covers that one). + if: ${{ !cancelled() && steps.swiftlint.outcome == 'success' }} + run: swiftlint lint --strict --no-cache secrets: runs-on: ubuntu-latest env: - TOOLS_DIR: /home/runner/.cache/ci-tools GITLEAKS_VERSION: 8.30.1 GITLEAKS_SHA256: 551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb @@ -188,33 +163,28 @@ jobs: with: fetch-depth: 0 # every commit, not only the tip: a secret removed later is still leaked - - name: Restore cached gitleaks - id: cache-gitleaks - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + - name: Setup Node.js (fetch-tool) + # Node only: the fetch-tool script needs no dependencies, so no yarn install here. + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: - path: ${{ env.TOOLS_DIR }}/gitleaks_${{ env.GITLEAKS_VERSION }}_linux_x64.tar.gz - key: ci-tools-${{ runner.os }}-gitleaks-${{ env.GITLEAKS_SHA256 }} + node-version-file: .nvmrc + package-manager-cache: false - - name: Scan the git history for secrets (gitleaks, checksum-pinned) + - name: Fetch gitleaks # The CLI, pinned like the other tools; gitleaks-action needs a license key on organisation repos. - run: | - mkdir -p "$TOOLS_DIR" - archive="$TOOLS_DIR/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" - [ -f "$archive" ] || { curl -sSfL -o "$archive.part" "https://github.com/gitleaks/gitleaks/releases/download/v$GITLEAKS_VERSION/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" && echo "$GITLEAKS_SHA256 $archive.part" | sha256sum -c - && mv "$archive.part" "$archive"; } - echo "$GITLEAKS_SHA256 $archive" | sha256sum -c - - tar -xzf "$archive" -C "$RUNNER_TEMP" gitleaks - # --log-opts: HEAD limits the scan to the checked-out commit's history (without it gitleaks - # runs `git log --all`, and fetch-depth 0 fetches every branch, so a key on any stale branch - # would fail every run); --diff-merges=separate also scans what a merge commit adds itself - # (a conflict resolution), which plain `git log -p` skips. - "$RUNNER_TEMP/gitleaks" git --no-banner --redact --config .gitleaks.toml --log-opts="--diff-merges=separate HEAD" . - - - name: Save downloaded gitleaks to the cache - if: always() && steps.cache-gitleaks.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + uses: ./.github/actions/fetch-tool with: - path: ${{ env.TOOLS_DIR }}/gitleaks_${{ env.GITLEAKS_VERSION }}_linux_x64.tar.gz - key: ci-tools-${{ runner.os }}-gitleaks-${{ env.GITLEAKS_SHA256 }} + name: gitleaks + url: https://github.com/gitleaks/gitleaks/releases/download/v${{ env.GITLEAKS_VERSION }}/gitleaks_${{ env.GITLEAKS_VERSION }}_linux_x64.tar.gz + sha256: ${{ env.GITLEAKS_SHA256 }} + archive-path: gitleaks + + - name: Scan the git history for secrets (gitleaks) + # --log-opts: HEAD limits the scan to the checked-out commit's history (without it gitleaks + # runs `git log --all`, and fetch-depth 0 fetches every branch, so a key on any stale branch + # would fail every run); --diff-merges=separate also scans what a merge commit adds itself + # (a conflict resolution), which plain `git log -p` skips. + run: gitleaks git --no-banner --redact --config .gitleaks.toml --log-opts="--diff-merges=separate HEAD" . supply-chain: # Google's reusable workflow (the action alone is not meant to be used directly). No SARIF @@ -237,6 +207,11 @@ jobs: native-tests: runs-on: ubuntu-latest + # The lockfile check and the Android step run even when an earlier check failed, so one run + # reports all of them; they still skip when the wrapper validation, setup or JDK did not pass + # (the JDK step runs only after both). The documents step builds and runs the converter the + # first step tests, so it keeps the default and skips after a converter failure. + steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -250,6 +225,7 @@ jobs: uses: ./.github/actions/setup - name: Install JDK + id: jdk uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: 'zulu' @@ -262,6 +238,7 @@ jobs: # The lockfiles are what OSV-Scanner (supply-chain) scans: a lock that no longer matches the # declared dependencies would hide a downgrade or a removed library and scan versions that do # not ship. Rewrite both and fail on any difference. + if: ${{ !cancelled() && steps.jdk.outcome == 'success' }} run: | tools/remote-compose-json/gradlew -p tools/remote-compose-json dependencies --write-locks --console=plain > /dev/null example/android/gradlew -p example/android :app:dependencies --configuration releaseRuntimeClasspath --write-locks --console=plain > /dev/null @@ -280,10 +257,13 @@ jobs: exit 1 fi - - name: Android unit tests (host value resolution) and Android Lint (new findings only) - # Lint's pre-existing findings are in android/lint-baseline.xml. remoteComposeStrictLint makes - # warnings fail here only; apps that lint the library keep lint's default (errors only). - run: example/android/gradlew -p example/android :react-native-remote-compose:testDebugUnitTest :react-native-remote-compose:lintDebug -PremoteComposeStrictLint=true --console=plain + - name: Android unit tests (host value resolution) and Android Lint + # No lint baseline: any finding fails. remoteComposeStrictLint makes warnings fail here only; + # apps that lint the library keep lint's default (errors only). + # --continue: lint runs and reports even when a unit test fails (lint does not depend on the + # tests), and the step still fails on either. + if: ${{ !cancelled() && steps.jdk.outcome == 'success' }} + run: example/android/gradlew -p example/android :react-native-remote-compose:testDebugUnitTest :react-native-remote-compose:lintDebug -PremoteComposeStrictLint=true --continue --console=plain build-library: runs-on: ubuntu-latest @@ -325,7 +305,7 @@ jobs: TURBO_CACHE_STATUS=$(node -p "($(yarn turbo run build:android --cache-dir="${{ env.TURBO_CACHE_DIR }}" --dry=json)).tasks.filter(t => t.task === 'build:android' && t.command !== '').every(t => t.cache.status === 'HIT') ? 'HIT' : 'MISS'") if [[ $TURBO_CACHE_STATUS == "HIT" ]]; then - echo "turbo_cache_hit=1" >> $GITHUB_ENV + echo "turbo_cache_hit=1" >> "$GITHUB_ENV" fi - name: Install JDK @@ -341,7 +321,7 @@ jobs: /bin/bash -c "yes | $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --licenses > /dev/null" # The runner image can carry an incomplete NDK directory, which AGP then refuses # ("did not have a source.properties file"); install the version React Native asks for. - $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --install "ndk;27.1.12297006" > /dev/null + "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --install "ndk;27.1.12297006" > /dev/null - name: Cache Gradle @@ -392,7 +372,7 @@ jobs: TURBO_CACHE_STATUS=$(node -p "($(yarn turbo run build:ios --cache-dir="${{ env.TURBO_CACHE_DIR }}" --dry=json)).tasks.filter(t => t.task === 'build:ios' && t.command !== '').every(t => t.cache.status === 'HIT') ? 'HIT' : 'MISS'") if [[ $TURBO_CACHE_STATUS == "HIT" ]]; then - echo "turbo_cache_hit=1" >> $GITHUB_ENV + echo "turbo_cache_hit=1" >> "$GITHUB_ENV" fi - name: Use appropriate Xcode version diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c70c400..85a65a7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -69,20 +69,22 @@ yarn lint --fix ### Static analysis -CI runs these checks and fails on any new finding, warnings included (`yarn lint` runs with +CI runs these checks and fails on any finding, warnings included (`yarn lint` runs with `--max-warnings 0`, Android Lint with `-PremoteComposeStrictLint=true`, which turns on `warningsAsErrors`). Without that property Android Lint fails on errors only: `android/` ships in the -npm package, and an app that lints the library with a newer lint must not fail on a new warning. Findings that predate a tool are recorded -in a baseline; fix one and shrink its baseline in the same change. What a baseline matches differs: - -- ESLint's `eslint-suppressions.json` counts violations per file and rule, not per location. A fixed - violation whose count is not lowered fails (`yarn lint --prune-suppressions` lowers it), but a new - violation of the same rule in the same file passes if an old one is fixed in the same change. -- Android Lint and detekt: an entry that no longer matches a finding does not fail (Android Lint - only prints that it was not found), so remove it with the fix. -- detekt matches an entry by rule, file name (not path) and signature (the enclosing declaration or - the flagged code), not by line. A new finding with the same rule and signature in a file of the same - name, such as a second `catch (e: Exception)` in `Main.kt`, is hidden by the old entry. +npm package, and an app that lints the library with a newer lint must not fail on a new warning. + +No tool has a baseline of old findings. A finding is fixed, or, when the code is right as it is, +suppressed on the narrowest element with the reason next to it: + +- ESLint: `// eslint-disable-next-line -- `. A disable that no longer matches a + finding is reported, and fails with `--max-warnings 0`. No bulk suppressions + (`eslint-suppressions.json`): they count per file and rule, so a fixed violation can hide a new one. +- detekt: `@Suppress("")` on the catch parameter, expression or declaration, with a comment. + Its baseline matched by file name and signature, so one entry hid every `catch (e: Exception)` in a + file of that name. +- Android Lint: `@SuppressLint("")` (or `@Suppress`, in code the JVM-only CLI also compiles), with + a comment. - knip fails on an `ignoreDependencies` entry that is no longer needed. A `@knipignore` tag covers only the export it is on; knip does not report one left on an export that became used. - Android Lint skips the checks whose result changes with no code change (newer versions published, @@ -90,22 +92,21 @@ in a baseline; fix one and shrink its baseline in the same change. What a baseli | Area | Tool (pinned in CI) | Run locally | Baseline | | --- | --- | --- | --- | -| TypeScript | ESLint with typescript-eslint `strictTypeChecked` | `yarn lint` | `eslint-suppressions.json` (`yarn lint --prune-suppressions` after a fix) | +| TypeScript | ESLint with typescript-eslint `strictTypeChecked` | `yarn lint` | none | | TypeScript | `tsc` (`strict`, `noUncheckedIndexedAccess`) | `yarn typecheck` | none | | All workspaces | knip 6.45.1 (unused files, exports, dependencies) | `yarn knip` | `ignoreDependencies` in `knip.jsonc`; `@knipignore` on single exports | | Kotlin | ktlint 1.8.0 | `ktlint "android/src/**/*.kt" "!android/src/main/java/com/remotecompose/contract/**" "tools/remote-compose-json/**/*.kt" "tools/remote-compose-json/*.kts"` | none | -| Kotlin | detekt 1.23.8 | see the `lint` job in `.github/workflows/ci.yml` | `detekt-baseline.xml` | -| Android | Android Lint | `example/android/gradlew -p example/android :react-native-remote-compose:lintDebug -PremoteComposeStrictLint=true` | `android/lint-baseline.xml` (`updateLintBaseline`) | +| Kotlin | detekt 1.23.8 | `detekt --build-upon-default-config --config detekt.yml --input android/src,tools/remote-compose-json/src --excludes '**/contract/**'` | none | +| Android | Android Lint | `example/android/gradlew -p example/android :react-native-remote-compose:lintDebug -PremoteComposeStrictLint=true` | none | | Swift | SwiftFormat 0.64.7 | `swiftformat --lint ios` | none | | Swift | SwiftLint 0.65.1 | `swiftlint lint --strict` | none | | Secrets | gitleaks 8.30.1, every commit reachable from `HEAD` | `gitleaks git --config .gitleaks.toml --log-opts="--diff-merges=separate HEAD" .` | allowlist in `.gitleaks.toml` | | Dependencies | OSV-Scanner | `osv-scanner scan --config=osv-scanner.toml --lockfile=yarn.lock --lockfile=example/Gemfile.lock --lockfile=example/android/app/gradle.lockfile --lockfile=tools/remote-compose-json/gradle.lockfile` | `osv-scanner.toml` | | Versions | `scripts/check-versions.ts` (copies of native dependency versions agree) | `yarn lint` | none | -To regenerate the detekt baseline after a fix, run detekt as in CI with `--create-baseline`. - -Use the versions in the table locally (CI downloads exactly those, checksum-verified; see the `env` of -the `lint` job in `.github/workflows/ci.yml`). CI runs SwiftLint's statically linked Linux build +Use the versions in the table locally. CI downloads exactly those through +`.github/actions/fetch-tool`, which checks each file's SHA-256 (pinned in the `env` of the `lint` and +`secrets` jobs in `.github/workflows/ci.yml`) before using it, cached or not. CI runs SwiftLint's statically linked Linux build (`swiftlint-static`), which has no SourceKit and skips the rules that need it (such as `statement_position`; SwiftFormat covers that one). SwiftLint on macOS runs those rules too, so it can report findings CI does not. diff --git a/android/build.gradle b/android/build.gradle index fd9f2c6..3378793 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -117,9 +117,7 @@ android { "PlaySdkIndexGenericIssues", "PlaySdkIndexDeprecated", ] - // Findings that predate running lint in CI; only new ones fail. Regenerate with - // `:react-native-remote-compose:updateLintBaseline` after fixing one. - baseline = file("lint-baseline.xml") + // No baseline: a finding is fixed, or suppressed where it is (@SuppressLint) with the reason. } } diff --git a/android/lint-baseline.xml b/android/lint-baseline.xml deleted file mode 100644 index 9a1216c..0000000 --- a/android/lint-baseline.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - diff --git a/android/src/main/java/com/remotecompose/DocumentLoader.kt b/android/src/main/java/com/remotecompose/DocumentLoader.kt index 52d2fc5..f383a0f 100644 --- a/android/src/main/java/com/remotecompose/DocumentLoader.kt +++ b/android/src/main/java/com/remotecompose/DocumentLoader.kt @@ -1,5 +1,6 @@ package com.remotecompose +import android.annotation.SuppressLint import android.content.ContentResolver import android.content.Context import android.net.Uri @@ -48,6 +49,9 @@ internal object DocumentLoader { } private suspend fun loadUri(context: Context, source: DocumentSource.Uri): ByteArray { + // UseKtx: toUri() is core-ktx, which this library does not declare. Declaring it would put a + // minimum core-ktx version on every app for a one-line wrapper around Uri.parse. + @SuppressLint("UseKtx") val uri = Uri.parse(source.uri) return when { URLUtil.isNetworkUrl(source.uri) -> loadHttp(source) @@ -68,7 +72,8 @@ internal object DocumentLoader { val request = Request.Builder() .url(source.uri) - .headers(Headers.headersOf(*source.headers.toTypedArray())) + // A few header strings copied once per request: the copy the rule warns about is negligible. + .headers(@Suppress("SpreadOperator") Headers.headersOf(*source.headers.toTypedArray())) .build() val call = httpClient.newCall(request) return suspendCancellableCoroutine { continuation -> @@ -87,6 +92,8 @@ internal object DocumentLoader { } } + // One throw per way a response can fail, each with its own message for onError. + @Suppress("ThrowsCount") private fun readBody(response: Response, uri: String): ByteArray { if (!response.isSuccessful) throw IOException("HTTP ${response.code} for $uri") val body = response.body ?: throw IOException("Empty response for $uri") diff --git a/android/src/main/java/com/remotecompose/PreparedDocument.kt b/android/src/main/java/com/remotecompose/PreparedDocument.kt index fd9591c..1075b99 100644 --- a/android/src/main/java/com/remotecompose/PreparedDocument.kt +++ b/android/src/main/java/com/remotecompose/PreparedDocument.kt @@ -67,6 +67,7 @@ private suspend fun stage(code: ErrorCode, block: suspend () -> T): T = try block() } catch (e: CancellationException) { throw e -} catch (e: Exception) { +} catch (@Suppress("TooGenericExceptionCaught") e: Exception) { + // Every failure of a stage, whatever AndroidX or rc-players throws, reaches JS as that stage's code. throw RemoteComposeException(code, e.message ?: e.toString(), e) } diff --git a/android/src/main/java/com/remotecompose/RemoteComposeModule.kt b/android/src/main/java/com/remotecompose/RemoteComposeModule.kt index 4549917..23c95fc 100644 --- a/android/src/main/java/com/remotecompose/RemoteComposeModule.kt +++ b/android/src/main/java/com/remotecompose/RemoteComposeModule.kt @@ -20,8 +20,9 @@ class RemoteComposeModule(reactContext: ReactApplicationContext) : NativeRemoteC executor.execute { try { promise.resolve(Base64.encodeToString(JsonDocuments.toRc(json), Base64.NO_WRAP)) - } catch (e: Exception) { - // A conversion failure is a `load` failure, as the view reports it for `{ json }`. + } catch (@Suppress("TooGenericExceptionCaught") e: Exception) { + // Anything AndroidX's parser throws rejects the promise (uncaught on this executor it + // would crash the app), as a `load` failure, as the view reports it for `{ json }`. promise.reject(ErrorCode.LOAD.wireValue, e.message ?: e.toString(), e) } } diff --git a/android/src/main/java/com/remotecompose/RemoteComposeView.kt b/android/src/main/java/com/remotecompose/RemoteComposeView.kt index 374bfd4..0a768e2 100644 --- a/android/src/main/java/com/remotecompose/RemoteComposeView.kt +++ b/android/src/main/java/com/remotecompose/RemoteComposeView.kt @@ -1,5 +1,6 @@ package com.remotecompose +import android.annotation.SuppressLint import android.util.Log import android.widget.FrameLayout import androidx.annotation.MainThread @@ -32,6 +33,11 @@ import kotlinx.coroutines.launch * is therefore confined to the main thread, and a newer load cancels the older one before it can * apply a stale result. */ +// ViewConstructor: React Native creates it only through RemoteComposeViewManager, with the +// ThemedReactContext it needs; it is never inflated from XML or created by layout tools. +// TooManyFunctions: one setter per React prop (Codegen's interface), the rest is the load lifecycle. +@SuppressLint("ViewConstructor") +@Suppress("TooManyFunctions") class RemoteComposeView(private val reactContext: ThemedReactContext) : FrameLayout(reactContext) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private val typefaces = RcTypefaceLoader.Default diff --git a/android/src/main/java/com/remotecompose/RemoteComposeViewManager.kt b/android/src/main/java/com/remotecompose/RemoteComposeViewManager.kt index 893f3df..4f34333 100644 --- a/android/src/main/java/com/remotecompose/RemoteComposeViewManager.kt +++ b/android/src/main/java/com/remotecompose/RemoteComposeViewManager.kt @@ -13,6 +13,7 @@ import com.remotecompose.contract.Theme /** Maps Codegen's props interface to [RemoteComposeView]; wire values become typed here. */ @ReactModule(name = RemoteComposeViewManager.NAME) +@Suppress("TooManyFunctions") // one override per React prop and view-manager callback class RemoteComposeViewManager : SimpleViewManager(), RemoteComposeViewManagerInterface { diff --git a/detekt-baseline.xml b/detekt-baseline.xml deleted file mode 100644 index 0b13cdc..0000000 --- a/detekt-baseline.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - MagicNumber:Main.kt$3 - MaxLineLength:Main.kt$"usage: remote-compose-json in.json out.rc | ${Flags.DIR} in/ out/ | ${Flags.DUMP} doc.rc | ${Flags.ROUNDTRIP} doc.rc" - SpreadOperator:DocumentLoader.kt$DocumentLoader$(*source.headers.toTypedArray()) - ThrowsCount:DocumentLoader.kt$DocumentLoader$private fun readBody(response: Response, uri: String): ByteArray - TooGenericExceptionCaught:Main.kt$e: Exception - TooGenericExceptionCaught:PreparedDocument.kt$e: Exception - TooGenericExceptionCaught:RemoteComposeModule.kt$RemoteComposeModule$e: Exception - TooManyFunctions:RemoteComposeView.kt$RemoteComposeView : FrameLayout - TooManyFunctions:RemoteComposeViewManager.kt$RemoteComposeViewManager : SimpleViewManagerRemoteComposeViewManagerInterface - - diff --git a/detekt.yml b/detekt.yml index 73c04de..465853a 100644 --- a/detekt.yml +++ b/detekt.yml @@ -1,5 +1,6 @@ # detekt: applied on top of its default configuration (--build-upon-default-config). -# Findings that predate detekt are in detekt-baseline.xml; CI fails on any new one. +# No baseline: CI fails on any finding. One that is right as it is gets @Suppress("Rule") on the +# narrowest element (a catch parameter, an expression, a function), with a comment saying why. naming: FunctionNaming: # Compose's convention, as in .editorconfig for ktlint: composables are PascalCase nouns. diff --git a/eslint-suppressions.json b/eslint-suppressions.json deleted file mode 100644 index 4d04e49..0000000 --- a/eslint-suppressions.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "example-shared/src/App.tsx": { - "@typescript-eslint/no-floating-promises": { - "count": 1 - } - }, - "example-shared/src/documents.ts": { - "@typescript-eslint/no-require-imports": { - "count": 4 - }, - "@typescript-eslint/no-unsafe-assignment": { - "count": 4 - } - }, - "example-shared/src/screens/JsonScreen.tsx": { - "@typescript-eslint/no-misused-promises": { - "count": 1 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 2 - } - }, - "example-shared/src/screens/NetworkScreen.tsx": { - "@typescript-eslint/no-non-null-assertion": { - "count": 1 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 1 - } - }, - "example-shared/src/screens/PerformanceScreen.tsx": { - "@typescript-eslint/no-floating-promises": { - "count": 1 - }, - "@typescript-eslint/no-misused-promises": { - "count": 1 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 3 - } - }, - "scripts/__tests__/generate-native-contract.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 6 - } - }, - "scripts/__tests__/host-cpu.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 3 - } - }, - "scripts/__tests__/lib.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 5 - } - }, - "scripts/__tests__/package-exports.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 2 - } - }, - "scripts/__tests__/perf-parse.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 6 - } - }, - "scripts/__tests__/stats.test.ts": { - "@typescript-eslint/no-floating-promises": { - "count": 3 - } - }, - "scripts/generate-native-contract.ts": { - "@typescript-eslint/no-non-null-assertion": { - "count": 2 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 4 - } - }, - "scripts/lib.ts": { - "@typescript-eslint/no-non-null-assertion": { - "count": 1 - }, - "@typescript-eslint/no-unsafe-return": { - "count": 1 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 3 - } - }, - "scripts/measure-perf.ts": { - "@typescript-eslint/prefer-promise-reject-errors": { - "count": 2 - }, - "@typescript-eslint/restrict-plus-operands": { - "count": 1 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 16 - } - }, - "scripts/stats.ts": { - "@typescript-eslint/no-non-null-assertion": { - "count": 3 - } - }, - "src/RemoteComposeView.native.tsx": { - "@typescript-eslint/no-empty-object-type": { - "count": 1 - } - }, - "src/__tests__/RemoteComposeView.test.tsx": { - "@typescript-eslint/no-non-null-assertion": { - "count": 2 - }, - "@typescript-eslint/no-unsafe-assignment": { - "count": 6 - }, - "@typescript-eslint/no-unsafe-member-access": { - "count": 1 - } - }, - "src/__tests__/index.test.ts": { - "@typescript-eslint/require-await": { - "count": 1 - } - }, - "src/__tests__/unsupportedPlatform.test.tsx": { - "@typescript-eslint/no-unsafe-assignment": { - "count": 1 - } - }, - "src/convert.ts": { - "@typescript-eslint/no-base-to-string": { - "count": 1 - }, - "@typescript-eslint/no-unnecessary-condition": { - "count": 2 - }, - "@typescript-eslint/restrict-template-expressions": { - "count": 2 - } - } -} \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs index f8ea0e7..a5bc763 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -44,8 +44,8 @@ export default defineConfig([ }, }, { - // Type-aware rules for TypeScript. Findings that predate them are recorded in - // eslint-suppressions.json (ESLint bulk suppressions), so only new code has to pass. + // Type-aware rules for TypeScript. No bulk suppressions (eslint-suppressions.json): a finding + // is fixed, or disabled on its line with `-- reason`; an unused disable fails (max-warnings 0). files: ['**/*.{ts,tsx}'], extends: tseslint.configs.strictTypeChecked.map(withoutTsPlugin), languageOptions: { @@ -54,6 +54,35 @@ export default defineConfig([ tsconfigRootDir: __dirname, }, }, + rules: { + '@typescript-eslint/no-floating-promises': [ + 'error', + { + // node:test's test() returns a promise that only reports completion: it is fulfilled + // when the test ends, failed or not, and the runner tracks the test itself. + allowForKnownSafeCalls: [ + { + from: 'package', + name: ['test', 'it', 'describe', 'suite'], + package: 'node:test', + }, + ], + }, + ], + '@typescript-eslint/restrict-template-expressions': [ + 'error', + { + // strictTypeChecked's options with numbers allowed, as in recommendedTypeChecked: a + // number has one string form, while booleans, null, arrays and objects stay errors. + allowAny: false, + allowBoolean: false, + allowNever: false, + allowNullish: false, + allowNumber: true, + allowRegExp: false, + }, + ], + }, }, { ignores: [ diff --git a/example-shared/src/App.tsx b/example-shared/src/App.tsx index 99271a1..78b3a76 100644 --- a/example-shared/src/App.tsx +++ b/example-shared/src/App.tsx @@ -65,7 +65,10 @@ export function DemoApp({ title }: { title: string }) { const launchLink: unknown = Platform.OS === 'ios' ? Settings.get('rcdemoLink') : undefined; if (typeof launchLink === 'string' && launchLink) apply(launchLink); - else Linking.getInitialURL().then(apply); + else + Linking.getInitialURL().then(apply, (error: unknown) => { + console.warn(`Could not read the launch link: ${String(error)}`); + }); const sub = Linking.addEventListener('url', ({ url }) => { apply(url); }); diff --git a/example-shared/src/documents.ts b/example-shared/src/documents.ts index edede15..60b16b1 100644 --- a/example-shared/src/documents.ts +++ b/example-shared/src/documents.ts @@ -1,16 +1,18 @@ /** * Demo documents. The JSON files are the source; `yarn documents` turns them into `.rc` with - * AndroidX's parser (tools/remote-compose-json), and both are bundled so the JSON path (Android) - * and the `.rc` path (both platforms) can be compared on the same screen. + * AndroidX's parser (tools/remote-compose-json). The `.rc` files are bundled for both platforms; + * pulse.json is bundled too, so the JSON path (Android) and the `.rc` path can be compared on the + * same screen. */ +import pulseJsonDocument from '../documents/json/pulse.json'; + +// Metro bundles a `.rc` file as an asset only through require(), which returns its asset id; the +// require() is untyped, hence the inline exceptions. +// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment -- Metro asset require export const productCardRc: number = require('../documents/rc/product_card.rc'); +// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment -- Metro asset require export const pulseRc: number = require('../documents/rc/pulse.rc'); -/** - * Bundled for a JSON-vs-`.rc` comparison that no screen shows yet. - * @knipignore - */ -export const productCardJson: object = require('../documents/json/product_card.json'); -export const pulseJson: object = require('../documents/json/pulse.json'); +export const pulseJson: object = pulseJsonDocument; /** Real AndroidX-captured documents, pinned to the rc-players 3.12.1 tag. */ const FIXTURES = diff --git a/example-shared/src/screens/JsonScreen.tsx b/example-shared/src/screens/JsonScreen.tsx index d3bc815..0b5915a 100644 --- a/example-shared/src/screens/JsonScreen.tsx +++ b/example-shared/src/screens/JsonScreen.tsx @@ -18,16 +18,18 @@ export function JsonScreen() { const [label, setLabel] = useState('Tap the circle'); const [status, setStatus] = useState(''); - const convert = async () => { + const convert = () => { const start = Date.now(); - try { - const base64 = await convertJsonToRc(pulseJson); - setStatus( - `converted: ${Math.floor((base64.length * 3) / 4)} bytes in ${Date.now() - start} ms` - ); - } catch (e) { - setStatus(`rejected: ${(e as Error).message}`); - } + convertJsonToRc(pulseJson).then( + (base64) => { + setStatus( + `converted: ${Math.floor((base64.length * 3) / 4)} bytes in ${Date.now() - start} ms` + ); + }, + (e: unknown) => { + setStatus(`rejected: ${e instanceof Error ? e.message : String(e)}`); + } + ); }; return ( diff --git a/example-shared/src/screens/NetworkScreen.tsx b/example-shared/src/screens/NetworkScreen.tsx index d4a2a26..ebe823e 100644 --- a/example-shared/src/screens/NetworkScreen.tsx +++ b/example-shared/src/screens/NetworkScreen.tsx @@ -11,7 +11,7 @@ export function NetworkScreen() { const [index, setIndex] = useState(0); const [lenient, setLenient] = useState(true); const [status, setStatus] = useState('loading…'); - const doc = networkDocuments[index]!; + const doc = networkDocuments[index] ?? networkDocuments[0]; const onLoad = (e: RemoteComposeLoadEvent) => { setStatus( diff --git a/example-shared/src/screens/PerformanceScreen.tsx b/example-shared/src/screens/PerformanceScreen.tsx index 9918183..1e33843 100644 --- a/example-shared/src/screens/PerformanceScreen.tsx +++ b/example-shared/src/screens/PerformanceScreen.tsx @@ -176,9 +176,18 @@ export function PerformanceScreen({ setRunning(false); }, [phase, post]); + // A run that throws would leave the screen "running…" and the benchmark script waiting for + // RC_PERF until its timeout; say why instead. + const start = useCallback(() => { + run().catch((error: unknown) => { + console.warn(`RC_PERF_FAILED ${String(error)}`); + setRunning(false); + }); + }, [run]); + useEffect(() => { - if (autorun) run(); - }, [autorun, run]); + if (autorun) start(); + }, [autorun, start]); return ( <> @@ -187,7 +196,7 @@ export function PerformanceScreen({