引言:为什么高级 CI/CD 对 Rust 项目很重要
基础的 Rust CI/CD 流水线固然不错,但在实际项目中,尤其是涉及多个平台、依赖项以及需要快速反馈时,简单的 cargo test 是不够的。高级的 GitHub Actions 配置可以将构建时间缩短 2-3 倍,自动在不同架构上检查代码,发布 crate 并执行 lint 检查。
在本文中,我们将深入探讨高级技术:依赖项缓存、针对 Windows/macOS/Linux 的构建矩阵、并行测试运行、发布到 crates.io 以及与 Clippy 的集成。
1. 优化构建时间:缓存和增量编译
Rust 在 CI 中最耗时的操作是编译依赖项。如果没有缓存,每次运行都需要重新下载和构建所有 crate。解决方案是使用 GitHub Actions 的内置缓存。
基本 target 目录缓存
jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions-rust-lang/setup-rust-toolchain@v1 - name: Cache Rust dependencies uses: actions/cache@v3 with: path: | ~/.cargo/registry ~/.cargo/git target key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - run: cargo build --release关键点:缓存键包含 Cargo.lock 的哈希值。如果依赖项没有变化,缓存会立即恢复。
用于测试和构建的高级缓存分离
对于大型项目,将 cargo build 和 cargo test 的缓存分开是有意义的,这样在构建发布版本时无需重新构建测试二进制文件:
- name: Cache cargo build uses: actions/cache@v3 with: path: | ~/.cargo/registry ~/.cargo/git target/debug/.fingerprint target/debug/build key: ${{ runner.os }}-build-${{ hashFiles('**/Cargo.lock') }}2. 构建矩阵:在所有平台上进行测试
Rust 可以编译到多种平台。为了确保在 Windows、macOS 和 Linux 上都能正常工作,我们使用矩阵策略。
三个操作系统的矩阵示例
jobs: test: strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] toolchain: [stable, beta] features: - default - all runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - uses: actions-rust-lang/setup-rust-toolchain@v1 with: toolchain: ${{ matrix.toolchain }} - name: Run tests run: cargo test --features ${{ matrix.features }}这种方法会自动创建 6 个并行任务(3 个操作系统 × 2 个工具链)。您可以添加对 nightly、arm64 架构或针对 WASM 的交叉编译的检查。
排除不必要的组合
strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] toolchain: [stable, nightly] exclude: - os: macos-latest toolchain: nightly # 不在 macOS 上测试 nightly3. Lint 检查、格式化和安全性
除了测试之外,高级 CI 还包括静态分析。我们将添加 clippy、rustfmt 和用于漏洞检查的 cargo-audit。
单独的 lint 任务
lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions-rust-lang/setup-rust-toolchain@v1 with: components: clippy, rustfmt - name: Check formatting run: cargo fmt --check - name: Clippy with warnings as errors run: cargo clippy -- -D warnings