Cargo Workflows

mohitmishra786/low-level-dev-skills/skills/rust/cargo-workflows

作者 mohitmishra786bdc58472fa9f無授權條款253 個星標收錄於 2026年10月9日更新於 2026年10月9日儲存庫3 個月前更新

Cargo workflow skill for Rust projects. Use when managing workspaces, feature flags, build scripts, cargo cache, incremental builds, dependency auditing, or CI configuration with Cargo. Activates on queries about cargo workspaces, Cargo.toml features, build.rs, cargo nextest, cargo deny, cargo check vs build, or Cargo.lock management.

AI 產生的概覽

引導代理處理 Rust 專案的 Cargo 工作區、特性旗標、建置指令碼、快取、測試與相依性稽核。

功能
此技能提供使用 Cargo 管理 Rust 專案的說明與設定範例,涵蓋工作區設定、特性旗標、build.rs 指令、增量建置與 CI 快取、cargo nextest、使用 cargo-audit 與 cargo-deny 進行相依性稽核,以及常用 cargo 指令。它產出的是指引與範例設定,而非可執行指令碼。
適用情境
適用於設定或維護 Cargo 工作區、設定特性旗標或建置指令碼、在 CI 中加速 Cargo 建置,或稽核 Rust 相依性。也適用於關於 cargo nextest、cargo deny、cargo check 與 build 的差異,或 Cargo.lock 管理的問題。
執行需求
不包含指令碼,僅為說明性內容。依範例操作可能需要 Rust 工具鏈與 Cargo,以及 cargo-nextest、cargo-audit、cargo-deny、cargo-machete、cargo-expand、cargo-edit 等選用工具,並需要網路存取來安裝它們。

Cargo Workflows

Purpose

Guide agents through Cargo workspaces, feature management, build scripts (build.rs), CI integration, incremental compilation, and the Cargo tool ecosystem.

Triggers

  • "How do I set up a Cargo workspace with multiple crates?"
  • "How do features work in Cargo?"
  • "How do I write a build.rs script?"
  • "How do I speed up Cargo builds in CI?"
  • "How do I audit my Rust dependencies?"
  • "What is cargo nextest and should I use it?"

Workflow

1. Workspace setup

text
my-project/├── Cargo.toml           # Workspace root├── Cargo.lock           # Single lock file for all members├── crates/│   ├── core/│   │   └── Cargo.toml│   ├── cli/│   │   └── Cargo.toml│   └── server/│       └── Cargo.toml└── tools/    └── codegen/        └── Cargo.toml
toml
# Workspace root Cargo.toml[workspace]members = [    "crates/core",    "crates/cli",    "crates/server",    "tools/codegen",]resolver = "2"   # Feature resolver v2 (required for edition 2021)
# Shared dependency versions (workspace.dependencies)[workspace.dependencies]serde = { version = "1", features = ["derive"] }tokio = { version = "1", features = ["full"] }anyhow = "1"
# Shared profile settings[profile.release]lto = "thin"codegen-units = 1
toml
# Member Cargo.toml[package]name = "myapp-core"version.workspace = trueedition.workspace = true
[dependencies]serde.workspace = true    # Inherit from workspaceanyhow.workspace = true

2. Feature flags

toml
[features]default = ["std"]
# Simple flagstd = []
# Feature that enables another featurefull = ["std", "async", "serde-support"]
# Feature with optional dependencyasync = ["dep:tokio"]serde-support = ["dep:serde", "serde/derive"]
[dependencies]tokio = { version = "1", optional = true }serde = { version = "1", optional = true }
bash
# Build with specific featurescargo build --features "async,serde-support"
# Build with no default featurescargo build --no-default-features
# Build with all featurescargo build --all-features
# Check feature combinationscargo check --no-default-featurescargo check --all-features

Feature gotchas:

  • Features are additive: once enabled anywhere in the dependency graph, they stay enabled
  • resolver = "2" prevents feature leakage between dev-dependencies and regular deps
  • Use dep:optional_dep syntax (edition 2021) to avoid implicit feature creation

3. Build scripts (build.rs)

rust
// build.rs (at crate root, runs before compilation)use std::env;use std::path::PathBuf;
fn main() {    // Re-run if these files change    println!("cargo:rerun-if-changed=build.rs");    println!("cargo:rerun-if-changed=wrapper.h");    println!("cargo:rerun-if-env-changed=MY_LIB_PATH");
    // Link a system library    println!("cargo:rustc-link-lib=mylib");    println!("cargo:rustc-link-search=/usr/local/lib");
    // Pass a cfg flag to Rust code    let target = env::var("TARGET").unwrap();    if target.contains("linux") {        println!("cargo:rustc-cfg=target_os_linux");    }
    // Set environment variable for downstream crates    println!("cargo:rustc-env=MY_GENERATED_VAR=value");
    // Generate bindings with bindgen    let bindings = bindgen::Builder::default()        .header("wrapper.h")        .generate()        .expect("Unable to generate bindings");
    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());    bindings.write_to_file(out_path.join("bindings.rs")).unwrap();}
println! directiveEffect
cargo:rerun-if-changed=FILERe-run build script if file changes
cargo:rerun-if-env-changed=VARRe-run if env var changes
cargo:rustc-link-lib=NAMELink library
cargo:rustc-link-search=PATHAdd library search path
cargo:rustc-cfg=FLAGEnable #[cfg(FLAG)] in code
cargo:rustc-env=KEY=VALSet env!("KEY") at compile time
cargo:warning=MSGEmit build warning

4. Incremental builds and CI caching

yaml
# GitHub Actions with sccache- uses: Swatinem/rust-cache@v2  with:    cache-on-failure: true    shared-key: "release-build"
# Or manual cache- uses: actions/cache@v3  with:    path: |      ~/.cargo/registry/index/      ~/.cargo/registry/cache/      ~/.cargo/git/db/      target/    key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
bash
# Warm cache locallycargo fetch                    # Download all deps without buildingcargo build --tests            # Build everything including test bins
# Check if incremental hurts release builds (it often does)[profile.release]incremental = false            # Default; leave false for release

5. cargo nextest (faster test runner)

bash
# Installcargo install cargo-nextest
# Run tests (parallel by default, better output)cargo nextest run
# Run with specific filtercargo nextest run test_name_pattern
# List tests without runningcargo nextest list
# Use in CI (JUnit output)cargo nextest run --profile ci

nextest.toml:

toml
[profile.ci]fail-fast = falsetest-threads = "num-cpus"retries = { backoff = "exponential", count = 2, delay = "1s" }
[profile.default]test-threads = "num-cpus"

6. Dependency management and auditing

bash
# Check for security advisoriescargo install cargo-auditcargo audit
# Deny specific licenses, duplicates, advisoriescargo install cargo-denycargo deny check
# Check for unused dependenciescargo install cargo-machetecargo machete
# Update dependenciescargo update                    # Update to compatible versionscargo update -p serde           # Update single packagecargo upgrade                   # Update to latest (cargo-edit)

deny.toml:

toml
[licenses]allow = ["MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause"]deny = ["GPL-2.0", "AGPL-3.0"]
[bans]multiple-versions = "warn"deny = [{ name = "openssl", reason = "Use rustls instead" }]
[advisories]ignore = []  # List advisory IDs to ignore

7. Useful cargo commands

bash
# Build only specific binarycargo build --bin myapp
# Build only specific examplecargo build --example myexample
# Run with argumentscargo run -- --flag arg1 arg2
# Expand macros (for debugging proc macros)cargo install cargo-expandcargo expand module::path
# Tree of dependenciescargo treecargo tree --duplicates      # Show crates with multiple versionscargo tree -i serde          # Who depends on serde?
# Cargo.toml metadatacargo metadata --format-version 1 | jq '.packages[].name'

For workspace patterns and dependency resolution details, see references/workspace-patterns.md [blocked].

Related skills

  • Use skills/rust/rustc-basics for compiler flags and profile configuration
  • Use skills/rust/rust-debugging for debugging Cargo-built binaries
  • Use skills/rust/rust-ffi for build.rs with C library bindings
  • Use skills/build-systems/cmake when integrating Rust into a CMake build

來源與署名

來源:mohitmishra786/low-level-dev-skills位於skills/rust/cargo-workflows提交bdc5847

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架