Search code examples
gradlegithub-actions

how to reuse gradle cache in GitHub workflow


I am trying to to keep the gradle cache in my GitHub workflow, but it is not working. I am new to gradle and am struggling to find out how/why I am unable to keep the gradle cache between workflow builds of my project

in my GitHub workflow file, I have two gradle caches. One of the gradle cache and the other one is the gradle wrapper:

      - name: Setup Gradle Dependencies Cache
        uses: actions/cache@v2
        with:
          path: ~/.gradle/caches
          key: ${{ runner.os }}-gradle-caches-${{ hashFiles('**/*.gradle', '**/*.gradle.kts') }}
      - name: Setup Gradle Wrapper Cache
        uses: actions/cache@v2
        with:
          path: ~/.gradle/wrapper
          key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }}

Locally a ./gradlew clean followed by a ./gradlew build will build my project in about 33 seconds... On GitHub, it takes 3 times as long (?): https://github.com/jactor-rises/jactor-persistence/runs/4794532441?check_suite_focus=true

How can I set up an effective cache of dependencies and wrapper in a GitHub workflow?


Solution

  • For workflows triggered in main branch:

    try gradle/gradle-build-action@v2 as mentioned in the gradle docs and github docs.

    name: Build Gradle project
    
    on:
      push:
    
    jobs:
      build-gradle-project:
        runs-on: ubuntu-latest
        steps:
        - name: Checkout project sources
          uses: actions/checkout@v3
        - name: Setup Gradle
          uses: gradle/gradle-build-action@v2
        - name: Run build with Gradle Wrapper
          run: ./gradlew build
    

    For workflows triggered in branches other than main:

    try gradle/gradle-build-action@v2 with cache-read-only: false

    1: for all branches

          - name: Setup Gradle
            uses: gradle/gradle-build-action@v2
            with:
             cache-read-only: false
    

    2: for specific branches

          - name: Setup Gradle
            uses: gradle/gradle-build-action@v2
            with:
             cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/release' }}
    

    Note: this option will most likely only work for workflows triggered by push because github.ref value might be different in other cases as mentioned here.