Unverified Commit 3a234be2 authored by Daz DeBoer's avatar Daz DeBoer Committed by GitHub
Browse files

Import wrapper validation into gradle/actions (#159)

Having a single repository to host all of the Gradle GitHub Actions will
provide numerous benefits:

1. Easier to stay on top of dependency updates
2. More frequent release cycle
3. Enable integration between different actions like automatic wrapper
validation with `setup-gradle`.
parents 3252e655 c1a61df4
Loading
Loading
Loading
Loading
+4
Changes for .github/workflows/ci-integ-test.yml: 4 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -179,3 +179,7 @@ jobs:
    uses: ./.github/workflows/integ-test-detect-java-toolchains.yml
    with:
      runner-os: '["ubuntu-latest"]'

  wrapper-validation:
    needs: [determine-suite, build-distribution]
    uses: ./.github/workflows/integ-test-wrapper-validation.yml
+68
Changes for .github/workflows/integ-test-wrapper-validation.yml: 68 added lines, 0 removed lines.
Original line number Diff line number Diff line
name: Test sample Kotlin DSL project

on:
  workflow_call:

jobs:
  # Integration test for successful validation of wrappers
  test-validation-success:
    name: 'Test: Validation success'
    runs-on: ubuntu-latest
    steps:
    - name: Checkout sources
      uses: actions/checkout@v4
    - name: Initialize integ-test
      uses: ./.github/actions/init-integ-test

    - name: Run wrapper-validation-action
      id: action-test
      uses: ./wrapper-validation
      with:
        # to allow the invalid wrapper jar present in test data
        allow-checksums: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

    - name: Check outcome
      env:
        # Evaluate workflow expressions here as env variable values instead of inside shell script
        # below to not accidentally inject code into shell script or break its syntax
        FAILED_WRAPPERS: ${{ steps.action-test.outputs.failed-wrapper }}
        FAILED_WRAPPERS_MATCHES: ${{ steps.action-test.outputs.failed-wrapper == '' }}
      run: |
        if [ "$FAILED_WRAPPERS_MATCHES" != "true" ] ; then
          echo "'outputs.failed-wrapper' has unexpected content: $FAILED_WRAPPERS"
          exit 1
        fi

  # Integration test for failing validation of wrappers
  test-validation-error:
    name: 'Test: Validation error'
    runs-on: ubuntu-latest
    steps:
    - name: Checkout sources
      uses: actions/checkout@v4
    - name: Initialize integ-test
      uses: ./.github/actions/init-integ-test

    - name: Run wrapper-validation-action
      id: action-test
      uses: ./wrapper-validation
      # Expected to fail; validated below
      continue-on-error: true

    - name: Check outcome
      env:
        # Evaluate workflow expressions here as env variable values instead of inside shell script
        # below to not accidentally inject code into shell script or break its syntax
        VALIDATION_FAILED: ${{ steps.action-test.outcome == 'failure' }}
        FAILED_WRAPPERS: ${{ steps.action-test.outputs.failed-wrapper }}
        FAILED_WRAPPERS_MATCHES: ${{ steps.action-test.outputs.failed-wrapper == 'sources/test/jest/wrapper-validation/data/invalid/gradle-wrapper.jar|sources/test/jest/wrapper-validation/data/invalid/gradlе-wrapper.jar' }}
      run: |
        if [ "$VALIDATION_FAILED" != "true" ] ; then
          echo "Expected validation to fail, but it didn't"
          exit 1
        fi

        if [ "$FAILED_WRAPPERS_MATCHES" != "true" ] ; then
          echo "'outputs.failed-wrapper' has unexpected content: $FAILED_WRAPPERS"
          exit 1
        fi
+94
Changes for .github/workflows/update-checksums-file.js: 94 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*
 * Updates the `wrapper-checksums.json` file
 *
 * This is intended to be executed by the GitHub workflow, but can also be run
 * manually.
 */

// @ts-check

const httpm = require('../../sources/node_modules/typed-rest-client/HttpClient')

const path = require('path')
const fs = require('fs')

/**
 * @returns {Promise<void>}
 */
async function main() {
  const httpc = new httpm.HttpClient(
    'gradle/wrapper-validation-action/update-checksums-workflow',
    undefined,
    {allowRetries: true, maxRetries: 3}
  )

  /**
   * @param {string} url
   * @returns {Promise<string>}
   */
  async function httpGetText(url) {
    const response = await httpc.get(url)
    return await response.readBody()
  }

  /**
   * @typedef {Object} ApiVersionEntry
   * @property {string} version - version name
   * @property {string=} wrapperChecksumUrl - wrapper checksum URL; not present for old versions
   * @property {boolean} snapshot - whether this is a snapshot version
   */

  /**
   * @returns {Promise<ApiVersionEntry[]>}
   */
  async function httpGetVersions() {
    return JSON.parse(
      await httpGetText('https://services.gradle.org/versions/all')
    )
  }

  const versions = (await httpGetVersions())
    // Only include versions with checksum
    .filter(e => e.wrapperChecksumUrl !== undefined)
    // Ignore snapshots; they are changing frequently so no point in including them in checksums file
    .filter(e => !e.snapshot)
  console.info(`Got ${versions.length} relevant Gradle versions`)

  // Note: For simplicity don't sort the entries but keep the order from the API; this also has the
  // advantage that the latest versions come first, so compared to appending versions at the end
  // this will not cause redundant Git diff due to trailing `,` being forbidden by JSON

  /**
   * @typedef {Object} FileVersionEntry
   * @property {string} version
   * @property {string} checksum
   */
  /** @type {FileVersionEntry[]} */
  const fileVersions = []
  for (const entry of versions) {
    /** @type {string} */
    // @ts-ignore
    const checksumUrl = entry.wrapperChecksumUrl
    const checksum = await httpGetText(checksumUrl)
    fileVersions.push({version: entry.version, checksum})
  }

  const jsonPath = path.resolve(
    __dirname,
    '..',
    '..',
    'sources',
    'src',
    'wrapper-validation',
    'wrapper-checksums.json'
  )
  console.info(`Writing checksums file to ${jsonPath}`)
  // Write pretty-printed JSON (and add trailing line break)
  fs.writeFileSync(jsonPath, JSON.stringify(fileVersions, null, 2) + '\n')
}

main().catch(e => {
  console.error(e)
  // Manually set error exit code, otherwise error is logged but script exits successfully
  process.exitCode = 1
})
+55
Changes for .github/workflows/update-checksums-file.yml: 55 added lines, 0 removed lines.
Original line number Diff line number Diff line
name: 'Update Wrapper checksums file'

on:
  # Run weekly (at arbitrary time)
  schedule:
    - cron: '24 5 * * 6'
  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write

jobs:
  update-checksums:
    name: Update checksums
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
          cache-dependency-path: sources/package-lock.json

      - name: Install dependencies
        run: |
          npm install [email protected] --no-save
        working-directory: sources

      - name: Update checksums file
        run: node ../.github/workflows/update-checksums-file.js
        working-directory: sources

      # If there are no changes, this action will not create a pull request
      - name: Create or update pull request
        uses: peter-evans/create-pull-request@v6
        with:
          branch: bot/wrapper-checksums-update
          commit-message: Update known wrapper checksums
          title: Update known wrapper checksums
          # Note: Unfortunately this action cannot trigger the regular workflows for the PR automatically, see
          # https://github.com/peter-evans/create-pull-request/blob/main/docs/concepts-guidelines.md#triggering-further-workflow-runs
          # Therefore suggest below to close and then reopen the PR
          body: |
            Automatically generated pull request to update the known wrapper checksums.

            In case of conflicts, manually run the workflow from the [Actions tab](https://github.com/gradle/wrapper-validation-action/actions/workflows/update-checksums-file.yml), the changes will then be force-pushed onto this pull request branch.
            Do not manually update the pull request branch; those changes might get overwritten.

            > [!IMPORTANT]  
            > GitHub workflows have not been executed for this pull request yet. Before merging, close and then directly reopen this pull request to trigger the workflows.
+23
Changes for README.md: 23 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -69,3 +69,26 @@ jobs:
```

See the [full action documentation](docs/dependency-submission.md) for more advanced usage scenarios.

## The `wrapper-validation` action

The `wrapper-validation` action validates the checksums of _all_ [Gradle Wrapper](https://docs.gradle.org/current/userguide/gradle_wrapper.html) JAR files present in the repository and fails if any unknown Gradle Wrapper JAR files are found.

The action should be run in the root of the repository, as it will recursively search for any files named `gradle-wrapper.jar`.

### Example workflow

```yaml
name: "Validate Gradle Wrapper"
on: [push, pull_request]

jobs:
  validation:
    name: "Validation"
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: gradle/actions/wrapper-validation@v3
```

See the [full action documentation](docs/wrapper-validation.md) for more advanced usage scenarios.
Loading