What to cache when building Rust using Gitlab CI or similar

Update: caching $RUSTUP_HOME and $CARGO_HOME does not work for me – I removed them.

When building your project with Gitlab CI or a similar build tool, you can end up spending a lot of time watching your build repeat the same steps over and over. This is especially frustrating when it mostly consists of downloading and compiling the same things we downloaded and compiled last time.

To mitigate this, we can ask Gitlab CI to cache things that will be the same next time.

For a Rust project, the most important thing to cache is target in the local directory.

Update: nope, incorrect But, if you are installing tools using rustup or cargo, it will really help if you cache those too. Fortunately, Rust knows where those are by using environment variables, and these are defined in the standard Rust Docker image.

Update: if anyone knows how to cache the output of rustup and cargo installations, let me know. I think I would need to push a Docker image to Dockerhub to do it?

We can make sure we’re caching as much as possible by adding a section like this to .gitlab-ci.yml:

        key: shared-cache
            - target/

If you add this to all your jobs, they will share a single cache between them, and cache the local target directory as well as any tools installed with rustup or cargo.

Here is a full example from my Evolve SVGs project:

image: rust:latest

    - rustup component add rustfmt
    - rustup target add wasm32-unknown-unknown
    - cargo install trunk wasm-bindgen-cli

    stage: deploy
        - echo "Publishing pages to" $CI_PAGES_URL
        - make deploy
        - mv dist public
        - public
        - main
        key: shared-cache
            - target/

    stage: test
        - make test
        key: shared-cache
            - target/

2 thoughts on “What to cache when building Rust using Gitlab CI or similar”

  1. The reason $CARGO_HOME & $RUSTUP_HOME caching does not work (on GitlabCI at least) might be that those files aren’t located inside the repo.

    The documentation (https://docs.gitlab.com/ee/ci/yaml/#cache) states that cached elements must be “An array of paths relative to the project directory”.

    Overriding $CARGO_HOME can solve this issue:

    One can then successfully cache the 4 folders listed here :

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.