GitLab CI Pipeline for Rust Projects
GitLab CI configuration for Rust projects with clippy linting, cargo test, and release builds. Includes target directory caching for faster compilation.
Detailed Explanation
Rust CI Pipeline in GitLab
Rust compilation is notoriously slow, making caching critical for practical CI pipelines. This configuration minimizes build times while maintaining thorough quality checks.
Pipeline Configuration
stages:
- check
- test
- build
variables:
CARGO_HOME: "$CI_PROJECT_DIR/.cargo"
fmt:
stage: check
image: rust:1.77-slim
script:
- rustup component add rustfmt
- cargo fmt -- --check
clippy:
stage: check
image: rust:1.77-slim
script:
- rustup component add clippy
- cargo clippy -- -D warnings
cache:
key: rust-cache
paths:
- .cargo/registry/
- target/
policy: pull-push
test:
stage: test
image: rust:1.77-slim
script:
- cargo test --all-features
cache:
key: rust-cache
paths:
- .cargo/registry/
- target/
policy: pull-push
artifacts:
paths:
- target/debug/
expire_in: 1 hour
build_release:
stage: build
image: rust:1.77-slim
script:
- cargo build --release
cache:
key: rust-cache
paths:
- .cargo/registry/
- target/
policy: pull
artifacts:
paths:
- target/release/
expire_in: 1 week
rules:
- if: '$CI_COMMIT_BRANCH == "main"'
Caching Strategy
Rust caches are large (often 1-2 GB) because they include compiled dependencies. Caching both .cargo/registry/ (downloaded crates) and target/ (compiled artifacts) dramatically reduces build times after the first run.
Clippy with -D warnings
The -D warnings flag promotes all clippy warnings to errors, ensuring code quality standards are enforced. This is stricter than the default but catches many common mistakes.
Release builds on main only
The rules section ensures that the expensive release build only runs on the main branch, saving CI minutes on feature branches.
Use Case
Use for Rust libraries, web services (Actix, Axum), CLI tools, and systems programming projects. The pipeline ensures code quality through formatting, linting, and testing before producing optimized release binaries.
Try It — GitLab CI Config Generator
Related Topics
GitLab CI Pipeline for Go Projects
Language Pipelines
Docker Build and Push in GitLab CI
Docker & Containers
GitLab CI Caching Strategies for Faster Pipelines
Caching & Artifacts
Conditional Job Execution with GitLab CI Rules
Pipeline Architecture
Multi-Stage GitLab CI Pipeline Architecture
Pipeline Architecture