如何使用缓存和工件加速 Gitlab CI 作业

Evg*_*ene 4 rust gitlab gitlab-ci

我希望我的 Rust 项目的 Gitlab 测试工作运行得更快。在本地,它重建得相当快,但在 gitlab 作业中,avery 构建作为第一个构建运行得很慢。寻找一种方法来使用以前管道中的工件或缓存来加速 Rust 测试和构建过程。

# .gitlab-ci.yml
stages:
  - test

test:
  stage: test
  image: rust:latest
  script:
    - cargo test
Run Code Online (Sandbox Code Playgroud)

cg9*_*909 8

Gitlab CI/ CD支持使用. 它只能缓存项目目录中的文件,因此 如果您还想缓存货物注册表,则需要使用环境变量。cache.gitlab-ci.ymlCARGO_HOME

您可以cache在顶层添加一个设置,为所有本身没有设置的作业设置缓存cache,并且可以将其添加到作业定义下方,以便为此类作业设置缓存配置。

请参阅关键字参考有关所有可能的配置选项,

下面是一个示例配置,它缓存货物注册表和临时构建文件,并将作业配置clippy为仅使用缓存而不写入缓存:

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

Run Code Online (Sandbox Code Playgroud)

如果你想从 CI 使用cargo publish,你应该添加.cargo到你的.gitignore文件中。否则cargo publish会显示错误,表明您的项目目录中有未提交的目录.cargo