示例代码
# .github/workflows/ci.yml
name: Rust CI/CD Pipeline
# 1. 触发条件
on:
push:
branches: [ "main", "develop" ]
pull_request:
branches: [ "main" ]
# 2. 环境变量
env:
CARGO_TERM_COLOR: always
# 3. 任务定义
jobs:
# --- 任务 A: 代码质量与规范检查 (Lint & Test) ---
lint-and-test:
runs-on: ubuntu-latest
steps:
# --- 检出代码 ---
- name: Checkout code
uses: actions/checkout@v6
# --- 安装 Rust 工具链 ---
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable # 推荐使用 dtolnay 的 action,比官方更灵活
with:
components: rustfmt, clippy
# --- 缓存 Rust 依赖 ---
- name: Cache Cargo dependencies
uses: Swatinem/rust-cache@v2 # 这是一个非常高效的缓存插件,比官方 cache 更懂 Rust
with:
cache-on-failure: true
# --- 强制执行规范 ---
- name: Check Formatting (rustfmt)
run: cargo fmt --all -- --check
# --- 代码分析 ---
- name: Lint (Clippy)
# -D warnings 会将警告升级为错误,强制开发者修复
run: cargo clippy --all-targets --all-features -- -D warnings
# --- 运行测试 ---
- name: Run Tests
run: cargo test --verbose
# --- 任务 B: 构建发布产物 (Build Artifacts) ---
build-release:
needs: lint-and-test # 只有在 lint 和测试通过后,才进行构建
runs-on: ${{ matrix.os }}
strategy:
# 矩阵(同时运行)
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
include:
- os: ubuntu-latest
target: x86_64-unknown-linux-gnu
artifact-name: my-app-linux
- os: macos-latest
target: x86_64-apple-darwin
artifact-name: my-app-macos
- os: windows-latest
target: x86_64-pc-windows-msvc
artifact-name: my-app-windows.exe
steps:
# --- 检出代码 ---
- name: Checkout code
uses: actions/checkout@v4
# --- 安装 Rust 工具链 ---
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
# --- 构建 Rust 项目 ---
- name: Build Release
run: cargo build --release --target ${{ matrix.target }}
# --- 上传构建产物 ---
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.artifact-name }}
path: target/${{ matrix.target }}/release/${{ matrix.artifact-name }}