Context: We’re building Java projects with Gradle, and we are in the process of migrating our CI builds from Jenkins to GitHub Actions.
In SonarCloud web UI (Project > Administration > Analysis Method
) it is possible to generate an example build workflow to use as a starting point for GitHub Actions.
I have some concerns that the example provided by SonarCloud may not reflect best practice. I’ll explain below.
For Gradle, the suggestion is like this:
- Update
build.gradle
to have this:
plugins {
id "org.sonarqube" version "4.4.1.3373"
}
sonar {
properties {
property "sonar.projectKey", "**********"
property "sonar.organization", "****"
property "sonar.host.url", "https://sonarcloud.io"
}
}
- Create or update
.github/workflows/build.yml
:
name: SonarCloud
on:
push:
branches:
- develop
pull_request:
types: [opened, synchronize, reopened]
jobs:
build:
name: Build and analyze
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: 17
distribution: 'zulu' # Alternative distribution options are available
- name: Cache SonarCloud packages
uses: actions/cache@v3
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: Cache Gradle packages
uses: actions/cache@v3
with:
path: ~/.gradle/caches
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
restore-keys: ${{ runner.os }}-gradle
- name: Build and analyze
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: ./gradlew build sonar --info
The build configures caching for Gradle (Cache Gradle packages
step) explicitly. However, my understanding is that this is discouraged - and that previously gradle-build-action was the recommended way to set up Gradle, and now it is the setup-gradle action.
Another question is about caching of ~/.sonar/cache
folder - is it safe to reuse the cache across both mainline branch, and pull request build branches? For example, setup-gradle
action by default only writes to cache from mainline branch builds, and pull request builds only read from cache.
Edit: A colleague pointed out that actions/cache@v3
is also deprecated - v4
is now the latest.