8

I wish the GitLab test job for my project on Rust would run faster. Locally, it rebuilds pretty fast, but in the GitLab job, every build runs slow as the first one. Looking for a way to use artifacts or cache from previous pipeline to speed up rust test and build process.

# .gitlab-ci.yml
stages:
  - test

test:
  stage: test
  image: rust:latest
  script:
    - cargo test

1 Answer 1

12

Gitlab CI/CD supports caching between CI jobs using the cache key in your .gitlab-ci.yml. It is only able to cache files in the project directory so you need to use the environment variable CARGO_HOME if you also want to cache the cargo registry.

You can add a cache setting at the top level to setup a cache for all jobs that don't have a cache setting themselves and you can add it below a job definition to setup a cache configuration for this kind of job.

See the keyword reference for all possible configuration options.

Here is one example configuration that caches the cargo registry and the temporary build files and configures the clippy job to only use the cache but not write to it:

stages:
  - test

cache: &global_cache          # Default cache configuration with YAML variable
                              # `global_cache` pointing to this block

  key: ${CI_COMMIT_REF_SLUG}  # Share cache between all jobs on one branch/tag

  paths:                      # Paths to cache
    - .cargo/bin
    - .cargo/registry/index
    - .cargo/registry/cache
    - target/debug/deps
    - target/debug/build
  policy: pull-push           # All jobs not setup otherwise pull from
                              # and push to the cache

variables:
  CARGO_HOME: ${CI_PROJECT_DIR}/.cargo # Move cargo data into the project
                                       # directory so it can be cached

# ...


test:
  stage: test
  image: rust:latest
  script:
    - cargo test


# only for demonstration, you can remove this block if not needed
clippy:
  stage: test
  image: rust:latest
  script:
    - cargo clippy # ...
  only:
    - master
  needs: []
  cache:
    <<: *global_cache  # Inherit the cache configuration `&global_cache` 
    policy: pull       # But only pull from the cache, don't push changes to it

If you want to use cargo publish from CI, you should then add .cargo to your .gitignore file. Otherwise cargo publish will show an error that there is an uncommitted directory .cargo in your project directory.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.