跳到主要内容

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代码风格一致
Lintcargo 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

相关链接