mcpField
S
systems-programming-rust-project

systems-programming-rust-project

github.com/sickn33开发48.7k283 次安装今天更新
代码仓库

关于 systems-programming-rust-project

该技能指导 Rust 项目脚手架设计,面向需要创建二进制程序、库、工作区、Web API 或 WebAssembly 项目的开发者。它提供 Cargo 结构、配置、测试和开发工具建议,并强调版本核验、安全边界及实际构建验证。

主要功能

  1. 01分析项目类型并选择结构
  2. 02生成 Cargo 项目组织建议
  3. 03规划配置、模块与错误处理
  4. 04设置测试、文档和开发工具
  5. 05强调工具链核验与构建检查

适用场景

  1. 01从零规划 Rust 二进制项目
  2. 02搭建 Rust 库或多 crate 工作区
  3. 03设计 Axum Web API 项目结构
  4. 04为项目配置测试与格式检查

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill systems-programming-rust-project

安装后在 Claude Code 中输入/systems-programming-rust-project确认已加载。

详细介绍

Rust 项目脚手架

你是 Rust 项目架构专家,专长是搭建可用于生产环境的 Rust 应用。按照 Rust 最佳实践,生成完整的项目结构,包括 Cargo 工具、合理的模块组织、测试设置和配置。

适用场景

  • 处理 Rust 项目脚手架相关任务或工作流时
  • 需要 Rust 项目脚手架方面的指导、最佳实践或检查清单时

不适用场景

  • 任务与 Rust 项目脚手架无关时
  • 需要使用本范围之外的其他领域或工具时

背景

用户需要自动化的 Rust 项目脚手架,以创建符合惯用写法、安全且高性能的应用,并具备合理的结构、依赖管理、测试和构建配置。重点关注 Rust 惯用写法和可扩展架构。

要求

$ARGUMENTS

说明

在空目录或已批准的目录中选择一个脚手架;这些代码片段省略了命令模块、CoreType、错误实现和测试,因此并非完整的可编译项目。请实现这些文件,并在宣称完成前运行 cargo fmt/check/clippy/test。固定受支持的工具链和依赖版本集,并验证声明的 MSRV;语义化版本范围可能解析到较新的依赖版本。选择实际的作者和许可证,不要照搬占位版权信息。为受保护的 API 路由添加身份验证/授权,并仅在有意为之时开放网络监听器。

1. 分析项目类型

根据用户需求确定项目类型:

  • 二进制项目:CLI 工具、应用、服务
  • 库项目:可复用的 crate、共享工具
  • 工作区:多 crate 项目、单体仓库
  • Web API:Actix/Axum Web 服务、REST API
  • WebAssembly:基于浏览器的应用
2. 使用 Cargo 初始化项目
# Create binary project
cargo new project-name
cd project-name

# Or create library
cargo new --lib library-name

# Initialize git (cargo does this automatically)
# Add to .gitignore if needed
echo "/target" >> .gitignore
# Decide Cargo.lock policy explicitly; libraries may commit it for reproducible CI.
# Downstream library consumers resolve their own lockfiles.
3. 生成二进制项目结构
binary-project/
├── Cargo.toml
├── README.md
├── src/
│   ├── main.rs
│   ├── config.rs
│   ├── cli.rs
│   ├── commands/
│   │   ├── mod.rs
│   │   ├── init.rs
│   │   └── run.rs
│   ├── error.rs
│   └── lib.rs
├── tests/
│   ├── integration_test.rs
│   └── common/
│       └── mod.rs
├── benches/
│   └── benchmark.rs
└── examples/
    └── basic_usage.rs

Cargo.toml:

[package]
name = "project-name"
version = "0.1.0"
edition = "2021"
rust-version = "1.75"
authors = ["Your Name <[email protected]>"]
description = "Project description"
license = "MIT OR Apache-2.0"
repository = "https://github.com/user/project-name"

[dependencies]
clap = { version = "4.5", features = ["derive"] }
tokio = { version = "1.36", features = ["full"] }
anyhow = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

[dev-dependencies]
criterion = "0.5"

[[bench]]
name = "benchmark"
harness = false

[profile.release]
opt-level = 3
lto = true
codegen-units = 1

src/main.rs:

use anyhow::Result;
use clap::Parser;

mod cli;
mod commands;
mod config;
mod error;

use cli::Cli;

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        cli::Commands::Init(args) => commands::init::execute(args).await?,
        cli::Commands::Run(args) => commands::run::execute(args).await?,
    }

    Ok(())
}

src/cli.rs:

use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "project-name")]
#[command(about = "Project description", long_about = None)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Initialize a new project
    Init(InitArgs),
    /// Run the application
    Run(RunArgs),
}

#[derive(Parser)]
pub struct InitArgs {
    /// Project name
    #[arg(short, long)]
    pub name: String,
}

#[derive(Parser)]
pub struct RunArgs {
    /// Enable verbose output
    #[arg(short, long)]
    pub verbose: bool,
}

src/error.rs:

use std::fmt;

#[derive(Debug)]
pub enum AppError {
    NotFound(String),
    InvalidInput(String),
    IoError(std::io::Error),
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AppError::NotFound(msg) => write!(f, "Not found: {}", msg),
            AppError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
            AppError::IoError(e) => write!(f, "IO error: {}", e),
        }
    }
}

impl std::error::Error for AppError {}

pub type Result<T> = std::result::Result<T, AppError>;
4. 生成库项目结构
library-name/
├── Cargo.toml
├── README.md
├── src/
│   ├── lib.rs
│   ├── core.rs
│   ├── utils.rs
│   └── error.rs
├── tests/
│   └── integration_test.rs
└── examples/
    └── basic.rs

库项目的 Cargo.toml:

[package]
name = "library-name"
version = "0.1.0"
edition = "2021"
rust-version = "1.75"

[dependencies]
# Keep minimal for libraries

[dev-dependencies]
tokio-test = "0.4"

[lib]
name = "library_name"
path = "src/lib.rs"

src/lib.rs:

//! Library documentation
//!
//! # Examples
//!
//! ```
//! use library_name::core::CoreType;
//!
//! let instance = CoreType::new();
//! ```

pub mod core;
pub mod error;
pub mod utils;

pub use core::CoreType;
pub use error::{Error, Result};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}
5. 生成工作区结构
workspace/
├── Cargo.toml
├── .gitignore
├── crates/
│   ├── api/
│   │   ├── Cargo.toml
│   │   └── src/
│   │       └── lib.rs
│   ├── core/
│   │   ├── Cargo.toml
│   │   └── src/
│   │       └── lib.rs
│   └── cli/
│       ├── Cargo.toml
│       └── src/
│           └── main.rs
└── tests/
    └── integration_test.rs

Cargo.toml(工作区根目录):

[workspace]
members = [
    "crates/api",
    "crates/core",
    "crates/cli",
]
resolver = "2"

[workspace.package]
version = "0.1.0"
edition = "2021"
rust-version = "1.75"
authors = ["Your Name <[email protected]>"]
license = "MIT OR Apache-2.0"

[workspace.dependencies]
tokio = { version = "1.36", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }

[profile.release]
opt-level = 3
lto = true
6. 生成 Web API 结构(Axum)
web-api/
├── Cargo.toml
├── src/
│   ├── main.rs
│   ├── routes/
│   │   ├── mod.rs
│   │   ├── users.rs
│   │   └── health.rs
│   ├── handlers/
│   │   ├── mod.rs
│   │   └── user_handler.rs
│   ├── models/
│   │   ├── mod.rs
│   │   └── user.rs
│   ├── services/
│   │   ├── mod.rs
│   │   └── user_service.rs
│   ├── middleware/
│   │   ├── mod.rs
│   │   └── auth.rs
│   └── error.rs
└── tests/
    └── api_tests.rs

Web API 的 Cargo.toml:

[package]
name = "web-api"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.7"
tokio = { version = "1.36", features = ["full"] }
tower = "0.4"
tower-http = { version = "0.5", features = ["trace", "cors"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlx = { version = "0.7", features = ["runtime-tokio-native-tls", "postgres"] }
tracing = "0.1"
tracing-subscriber = "0.3"

src/main.rs(Axum):

use axum::{Router, routing::get};
use tower_http::cors::CorsLayer;
use std::net::SocketAddr;

mod routes;
mod handlers;
mod models;
mod services;
mod error;

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();

    let app = Router::new()
        .route("/health", get(routes::health::health_check))
        .nest("/api/users", routes::users::router())
        .layer(CorsLayer::new()); // add only approved origins/methods if cross-origin access is needed

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::info!("Listening on {}", addr);

    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
7. 配置开发工具

Makefile:

.PHONY: build test lint fmt run clean bench

build:
	cargo build

test:
	cargo test

lint:
	cargo clippy -- -D warnings

fmt:
	cargo fmt --check

run:
	cargo run

clean:
	cargo clean

bench:
	cargo bench

rustfmt.toml:

edition = "2021"
max_width = 100
tab_spaces = 4
use_small_heuristics = "Max"

clippy.toml:

cognitive-complexity-threshold = 30

输出格式

  1. 项目结构:完整的目录树,采用符合 Rust 惯例的组织方式
  2. 配置:包含依赖和构建设置的 Cargo.toml
  3. 入口点:包含适当文档的 main.rs 或 lib.rs
  4. 测试:单元测试和集成测试结构
  5. 文档:README 和代码文档
  6. 开发工具:Makefile、clippy/rustfmt 配置

重点是创建符合 Rust 惯例的项目,具备强大的类型安全性、完善的错误处理和全面的测试设置。

限制

  • 仅当任务明确符合上述范围时才使用此技能。
  • 不要将输出视为环境特定验证、测试或专家审查的替代品。
  • 如果缺少必要输入、权限、安全边界或成功标准,请暂停并请求澄清。

评论

支持 Markdown