cargo-workflows — скилл для Claude Code: рабочие процессы Cargo в Rust
Скилл ведёт агента по воркспейсам Cargo, фичам, build.rs, кэшу сборки и аудиту зависимостей. Пригодится, когда Rust-проект разрастается до нескольких крейтов.
npx skills add mohitmishra786/low-level-dev-skills --skill cargo-workflows -a claude-codeЧто делает cargo-workflows
Скилл описывает семь участков работы с Cargo: настройку воркспейса, фича-флаги, скрипты build.rs, инкрементальную сборку и кэш в CI, cargo nextest, аудит зависимостей и повседневные команды. Агент получает готовые шаблоны Cargo.toml, таблицу директив println! для build-скриптов, конфиги nextest.toml и deny.toml.
Внутри — примеры кода, а не исполняемые скрипты. Воркспейс собирается из корневого манифеста с members и resolver = "2", общие версии зависимостей выносятся в [workspace.dependencies], а члены подключают их через serde.workspace = true. Отдельный блок про фичи: они аддитивны, поэтому включённая где-то в графе зависимостей фича остаётся включённой, и синтаксис dep:tokio нужен, чтобы не плодить неявные фичи.
Для аудита скилл ставит cargo-audit, cargo-deny и cargo-machete — каждый через cargo install. Это значит, что в окружении должен быть рабочий тулчейн Rust и доступ к crates.io. Кэш в GitHub Actions описан двумя вариантами: Swatinem/rust-cache@v2 или ручной actions/cache@v3 с ключом по хэшу Cargo.lock. Инкрементальная сборка для release-профиля советует оставить incremental = false — на релизных сборках она часто вредит.
Какие задачи решает
- разложить проект на несколько крейтов в одном воркспейсе
- разобраться, почему фича включилась в чужой зависимости
- написать build.rs с пересборкой по изменению файла
- ускорить сборку Rust в CI за счёт кэша
- проверить зависимости на уязвимости и лишние лицензии
Примеры запросов агенту
- Настрой воркспейс Cargo с крейтами core, cli и server и общими версиями зависимостей
- Почему у меня включилась фича tokio, хотя я её не просил? Разберись с резолвером фич
- Добавь в CI кэш Cargo и запусти тесты через cargo nextest
Как установить cargo-workflows
1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill cargo-workflows -a claude-code2Вручную: положить файлы
~/.claude/skills/cargo-workflows/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/cargo-workflows/
1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill cargo-workflows -a codex2Вручную: положить файлы
.agents/skills/cargo-workflows/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill cargo-workflows -a cursor2Вручную: положить файлы
.cursor/skills/cargo-workflows/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install mohitmishra786/low-level-dev-skills cargo-workflows2Вручную: положить файлы
.github/skills/cargo-workflows/SKILL.md1Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill cargo-workflows -a gemini-cli2Командой платформы
gemini skills install https://github.com/mohitmishra786/low-level-dev-skills --path skills/rust/cargo-workflowsВручную: положить файлы
.devin/skills/cargo-workflows/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add mohitmishra786/low-level-dev-skills --skill cargo-workflows -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о cargo-workflows
Как установить cargo-workflows в Claude?
Выполните npx skills add mohitmishra786/low-level-dev-skills --skill cargo-workflows -a claude-code. Скилл окажется в ~/.claude/skills/cargo-workflows/SKILL.md.
Что делает cargo-workflows?
Подсказывает агенту, как устроены воркспейсы, фичи, build-скрипты и кэширование сборки в Cargo. Активируется на вопросах про Cargo.toml, build.rs, cargo nextest, cargo deny и управление Cargo.lock.
Чем cargo nextest отличается от обычного cargo test?
Скилл описывает nextest как более быстрый раннер: тесты идут параллельно, вывод читаемее, а профиль ci в nextest.toml задаёт повторы с экспоненциальной задержкой и отключает fail-fast. Ставится отдельно командой cargo install cargo-nextest.
Исходный текст
SKILL.md · MIT
---
name: cargo-workflows
description: 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.
user-invocable: true
triggers:
- cargo workspace setup
- feature flags in Cargo.toml
- build.rs script
- cargo nextest
- cargo deny audit
- cargo incremental build
- manage Cargo.lock
- CI config for Rust with Cargo
---
# 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 = true
edition.workspace = true
[dependencies]
serde.workspace = true # Inherit from workspace
anyhow.workspace = true
```
### 2. Feature flags
```toml
[features]
default = ["std"]
# Simple flag
std = []
# Feature that enables another feature
full = ["std", "async", "serde-support"]
# Feature with optional dependency
async = ["dep:tokio"]
serde-support = ["dep:serde", "serde/derive"]
[dependencies]
tokio = { version = "1", optional = true }
serde = { version = "1", optional = true }
```
```bash
# Build with specific features
cargo build --features "async,serde-support"
# Build with no default features
cargo build --no-default-features
# Build with all features
cargo build --all-features
# Check feature combinations
cargo check --no-default-features
cargo 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!` directive | Effect |
|---------------------|--------|
| `cargo:rerun-if-changed=FILE` | Re-run build script if file changes |
| `cargo:rerun-if-env-changed=VAR` | Re-run if env var changes |
| `cargo:rustc-link-lib=NAME` | Link library |
| `cargo:rustc-link-search=PATH` | Add library search path |
| `cargo:rustc-cfg=FLAG` | Enable `#[cfg(FLAG)]` in code |
| `cargo:rustc-env=KEY=VAL` | Set `env!("KEY")` at compile time |
| `cargo:warning=MSG` | Emit 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 locally
cargo fetch # Download all deps without building
cargo 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
# Install
cargo install cargo-nextest
# Run tests (parallel by default, better output)
cargo nextest run
# Run with specific filter
cargo nextest run test_name_pattern
# List tests without running
cargo nextest list
# Use in CI (JUnit output)
cargo nextest run --profile ci
```
`nextest.toml`:
```toml
[profile.ci]
fail-fast = false
test-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 advisories
cargo install cargo-audit
cargo audit
# Deny specific licenses, duplicates, advisories
cargo install cargo-deny
cargo deny check
# Check for unused dependencies
cargo install cargo-machete
cargo machete
# Update dependencies
cargo update # Update to compatible versions
cargo update -p serde # Update single package
cargo 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 binary
cargo build --bin myapp
# Build only specific example
cargo build --example myexample
# Run with arguments
cargo run -- --flag arg1 arg2
# Expand macros (for debugging proc macros)
cargo install cargo-expand
cargo expand module::path
# Tree of dependencies
cargo tree
cargo tree --duplicates # Show crates with multiple versions
cargo tree -i serde # Who depends on serde?
# Cargo.toml metadata
cargo metadata --format-version 1 | jq '.packages[].name'
```
For workspace patterns and dependency resolution details, see [references/workspace-patterns.md](references/workspace-patterns.md).
## 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 · MIT · mohitmishra786/low-level-dev-skills