You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GitHub CI工作流中缓存Cargo包以加速构建?

如何在GitHub CI中缓存Cargo安装的二进制文件缩短构建时间

我有一个使用Cargo包的GitHub CI,每次运行CI时构建该包大约需要6分钟。请问是否可以缓存二进制文件,以便下次运行时无需重复构建?以下是我的CI配置:

name: "Verify the specs of concrete tests using bulloak"

on: "workflow_call"

jobs:
  bulloak-check:
    runs-on: "ubuntu-latest"
    steps:
      - name: "Check out the repo"
        uses: "actions/checkout@v4"

      - name: "Install Rust"
        uses: "actions-rs/toolchain@v1"
        with:
          toolchain: "stable"

      - name: "Install bulloak or use the cached version"
        run: "cargo install bulloak"

      - name: "Verify the concrete tests"
        run: "bulloak check test/integration/concrete/**/**.tree --skip-modifiers"

      - name: "Bulloak summary"
        run: |
          echo "## Bulloak result" >> $GITHUB_STEP_SUMMARY
          echo "✅ Passed" >> $GITHUB_STEP_SUMMARY

可以通过GitHub Actions的缓存功能缓存cargo install生成的二进制文件,直接跳过重复构建步骤,大幅节省时间。修改后的CI配置如下:

name: "Verify the specs of concrete tests using bulloak"

on: "workflow_call"

jobs:
  bulloak-check:
    runs-on: "ubuntu-latest"
    steps:
      - name: "Check out the repo"
        uses: "actions/checkout@v4"

      - name: "Install Rust"
        uses: "actions-rs/toolchain@v1"
        with:
          toolchain: "stable"

      - name: "Cache bulloak binary"
        id: cache-bulloak
        uses: actions/cache@v3
        with:
          path: ~/.cargo/bin/bulloak
          key: ${{ runner.os }}-bulloak-${{ hashFiles('~/.cargo/registry/index/**') }}
          restore-keys: |
            ${{ runner.os }}-bulloak-

      - name: "Install bulloak if not cached"
        if: steps.cache-bulloak.outputs.cache-hit != 'true'
        run: "cargo install bulloak"

      - name: "Verify the concrete tests"
        run: "bulloak check test/integration/concrete/**/**.tree --skip-modifiers"

      - name: "Bulloak summary"
        run: |
          echo "## Bulloak result" >> $GITHUB_STEP_SUMMARY
          echo "✅ Passed" >> $GITHUB_STEP_SUMMARY

关键改动说明

  • 新增缓存步骤:用actions/cache工具缓存~/.cargo/bin/bulloak二进制文件,这是cargo install最终生成的可执行文件路径
  • 缓存键设计:键值包含操作系统标识和Cargo索引的哈希值,确保当bulloak版本更新或依赖包变更时,自动触发重新安装,避免缓存过时
  • 条件安装:只有当缓存未命中时,才执行cargo install bulloak,缓存命中时直接跳过这一步
  • 回退缓存:restore-keys配置让GitHub Actions能匹配最近的缓存版本,进一步提高缓存命中率

如果后续想进一步优化,还可以缓存Cargo的registry目录(~/.cargo/registry)和target目录,但针对当前场景,直接缓存二进制文件已经能解决核心的6分钟构建耗时问题。

内容的提问来源于stack exchange,提问作者smol-ninja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:15:08