CI/CD
问题
Rust 项目的 CI/CD 如何配置?
答案
GitHub Actions 模板
.github/workflows/ci.yml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
CARGO_TERM_COLOR: always
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy, rustfmt
# 缓存依赖编译结果
- uses: Swatinem/rust-cache@v2
# 格式检查
- run: cargo fmt --all -- --check
# Lint 检查
- run: cargo clippy --all-targets --all-features -- -D warnings
# 编译检查
- run: cargo check --all-features
# 运行测试
- run: cargo test --all-features
# 安全审计
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: rustsec/audit-check@v2
with:
token: ${{ secrets.GITHUB_TOKEN }}
CI 检查项
| 检查 | 命令 | 作用 |
|---|---|---|
| 格式化 | cargo fmt --check | 代码风格一致 |
| Lint | cargo clippy -- -D warnings | 代码质量 |
| 编译 | cargo check | 类型检查 |
| 测试 | cargo test | 功能正确 |
| 安全审计 | cargo audit | 依赖漏洞 |
缓存优化
Swatinem/rust-cache 缓存 target/ 目录,可将 CI 时间从 5-10 分钟 降到 1-2 分钟。
常见面试问题
Q1: Rust CI 为什么比较慢?如何优化?
答案:
| 优化策略 | 效果 |
|---|---|
rust-cache action | 缓存编译产物,减少 50-80% 时间 |
cargo check 代替 cargo build | 快 2-3 倍 |
| 拆分 job 并行执行 | fmt/clippy/test 并行 |
sccache | 分布式编译缓存 |
| 减少 feature 组合 | 只测试必要的 feature |