Search code examples
rustgithub-actions

GitHub Actions cache Rust artifacts


Using GitHub Actions, I am unable to see a significant improvement from using cached artifacts produced from previous builds, when building with Rust's cargo.

I suspect I forgot something in the following code, what could be the problem here?

EDIT: Here are the logs if you want to have a look at them!

name: Rust

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

env:
  CARGO_TERM_COLOR: always

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - name: Cargo Cache
      uses: actions/cache@v1
      with:
        path: ~/.cargo
        key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.toml') }}-${{ hashFiles('**/Cargo.lock') }}
        restore-keys: |
          ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.toml') }}
          ${{ runner.os }}-cargo

    - name: Cargo Target Cache
      uses: actions/cache@v1
      with:
        path: target
        key: ${{ runner.os }}-cargo-target-${{ hashFiles('**/Cargo.toml') }}-${{ hashFiles('**/Cargo.lock') }}
        restore-keys: |
          ${{ runner.os }}-cargo-target-${{ hashFiles('**/Cargo.toml') }}
          ${{ runner.os }}-cargo-target

    - uses: actions/checkout@v2
    - name: Build
      run: cargo build --verbose --all --features "strict"
    - name: Run tests
      run: cargo test --verbose --all --features "strict"

Solution

  • I think I got it working now: build time reduced from 4 minutes down to 1m15s.

    The fixes I applied were:

    • I needed to first check out the repository to have the Cargo.toml file used in the hashing function for the cache (!).
    • **/Cargo.toml was refactored to Cargo.toml, so that the file is found for hashing.

    Here's the final rust.yaml:

    name: Rust
    
    on:
      push:
        branches: [ main ]
      pull_request:
        branches: [ main ]
    
    env:
      CARGO_TERM_COLOR: always
    
    jobs:
      build:
    
        runs-on: ubuntu-latest
    
        steps:
        - uses: actions/checkout@v2
        - name: Cargo Cache
          uses: actions/cache@v1
          with:
            path: ~/.cargo
            key: ${{ runner.os }}-cargo-${{ hashFiles('Cargo.toml') }}
            restore-keys: |
              ${{ runner.os }}-cargo-${{ hashFiles('Cargo.toml') }}
              ${{ runner.os }}-cargo
    
        - name: Cargo Target Cache
          uses: actions/cache@v1
          with:
            path: target
            key: ${{ runner.os }}-cargo-target-${{ hashFiles('Cargo.toml') }}
            restore-keys: |
              ${{ runner.os }}-cargo-target-${{ hashFiles('Cargo.toml') }}
              ${{ runner.os }}-cargo-target
    
        - name: Build
          run: cargo build --verbose --all --features "strict"
        - name: Run tests
          run: cargo test --verbose --all --features "strict"