本文档介绍如何从零开始构建一个标准化的 Rust CLI 项目,以 anthropic-config 工具为例。
项目概述
anthropic-config 是一个用于管理 Anthropic API 配置的 CLI 工具,支持:
- 自定义 API endpoint 配置
- 智谱 AI Big Model 预设配置
- 查看当前配置
完整构建流程
1. 创建项目结构
bash
# 在工作目录下创建新项目
cargo new anthropic-config
cd anthropic-config
生成的标准目录结构:
anthropic-config/
├── Cargo.toml # 项目配置文件
└── src/
└── main.rs # 程序入口
2. 配置 Cargo.toml
toml
[package]
name = "anthropic-config"
version = "0.1.0"
edition = "2021"
description = "CLI tool for managing Anthropic API configuration"
authors = ["Your Name <your.email@example.com>"]
[[bin]]
name = "anthropic-config"
path = "src/main.rs"
[dependencies]
3. 设计模块化架构
将代码按功能拆分为独立模块:
src/
├── main.rs # 程序入口,命令路由
├── cli.rs # CLI 参数解析和帮助信息
├── handlers.rs # 各子命令的业务逻辑
├── env.rs # 环境变量设置和持久化
└── utils.rs # 工具函数(输入读取、字符串处理等)
模块职责划分
main.rs - 入口点
rust
mod cli;
mod env;
mod handlers;
mod utils;
use cli::Command;
fn main() {
let cmd = cli::parse_command();
match cmd {
Command::Custom => handlers::handle_custom(),
Command::BigModel => handlers::handle_big_model(),
Command::Show => handlers::handle_show(),
Command::Unknown => cli::print_usage(),
}
}
cli.rs - 命令行解析
rust
use std::env;
pub enum Command {
Custom,
BigModel,
Show,
Unknown,
}
pub fn parse_command() -> Command {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
return Command::Unknown;
}
match args[1].as_str() {
"custom" => Command::Custom,
"big_model" => Command::BigModel,
"show" => Command::Show,
_ => Command::Unknown,
}
}
pub fn print_usage() {
println!("Anthropic Configuration Manager");
println!("Usage: anthropic-config <command>");
// ...
}
handlers.rs - 业务逻辑
rust
use crate::env::confirm_and_apply;
use crate::utils::{mask, read_required, read_with_default};
pub fn handle_custom() {
println!("Custom Anthropic configuration\n");
let base_url = read_required("ANTHROPIC_BASE_URL: ");
let token = read_required("ANTHROPIC_AUTH_TOKEN: ");
confirm_and_apply(&base_url, &token);
}
pub fn handle_show() {
let base_url = std::env::var("ANTHROPIC_BASE_URL")
.unwrap_or_else(|_| "<not set>".to_string());
println!("ANTHROPIC_BASE_URL : {}", base_url);
}
env.rs - 环境变量管理
rust
use std::process::Command;
use std::fs::OpenOptions;
use std::io::Write;
pub fn confirm_and_apply(base_url: &str, token: &str) {
// 设置当前进程环境变量
std::env::set_var("ANTHROPIC_BASE_URL", base_url);
// 持久化到系统
persist_env("ANTHROPIC_BASE_URL", base_url);
}
pub fn persist_env(key: &str, value: &str) -> Result<(), String> {
if cfg!(target_os = "windows") {
Command::new("cmd")
.args(["/C", "setx", key, value])
.status()
.map_err(|e| e.to_string())?;
} else {
// 写入 ~/.bashrc
let home = std::env::var("HOME")?;
let profile = format!("{}/.bashrc", home);
let mut f = OpenOptions::new()
.create(true).append(true).open(&profile)?;
writeln!(f, "\nexport {}=\"{}\"", key, value)?;
}
Ok(())
}
utils.rs - 工具函数
rust
use std::io::{self, Write};
pub fn read_line(prompt: &str) -> String {
print!("{}", prompt);
io::stdout().flush().unwrap();
let mut s = String::new();
io::stdin().read_line(&mut s).unwrap();
s.trim().to_string()
}
pub fn read_required(prompt: &str) -> String {
loop {
let v = read_line(prompt);
if !v.is_empty() {
return v;
}
println!("Value required.\n");
}
}
4. 编译和测试
bash
# 开发版本编译(快速,未优化)
cargo build
# 发布版本编译(优化,体积小)
cargo build --release
# 运行测试
cargo test
# 直接运行
cargo run -- show
5. 安装到系统
方法 1: Cargo Install(推荐)
bash
# 从本地路径安装
cargo install --path .
# 更新时重新安装
cargo install --path . --force
安装位置:
- Windows:
%USERPROFILE%\.cargo\bin\anthropic-config.exe - macOS/Linux:
~/.cargo/bin/anthropic-config
原理:
- 执行
cargo build --release编译 - 复制
target/release/anthropic-config到~/.cargo/bin/ - 该目录已在 PATH 中,可直接调用
方法 2: 手动复制
bash
# Windows
copy target\release\anthropic-config.exe C:\Windows\System32\
# macOS/Linux
sudo cp target/release/anthropic-config /usr/local/bin/
6. 配置 PATH
确保 Cargo bin 目录在系统 PATH 中:
Windows:
powershell
# 添加到系统环境变量
$env:Path += ";C:\Users\YourName\.cargo\bin"
# 或通过 GUI 设置
# 系统属性 > 高级 > 环境变量 > Path > 新建
macOS/Linux:
bash
# 添加到 ~/.bashrc 或 ~/.zshrc
export PATH="$HOME/.cargo/bin:$PATH"
# 重新加载配置
source ~/.bashrc
7. 使用工具
bash
# 查看帮助
anthropic-config
# 查看当前配置
anthropic-config show
# 自定义配置
anthropic-config custom
# 使用智谱 AI Big Model
anthropic-config big_model
开发工作流
日常开发流程
bash
# 1. 修改代码
vim src/main.rs
# 2. 快速测试
cargo run -- show
# 3. 运行测试
cargo test
# 4. 发布新版本
# 更新 Cargo.toml 中的版本号
# 重新安装
cargo install --path . --force
项目结构最佳实践
project-name/
├── .gitignore # Git 忽略文件
├── Cargo.toml # 项目配置
├── Cargo.lock # 依赖锁定(自动生成)
├── README.md # 项目文档
├── src/
│ ├── main.rs # 入口
│ ├── cli.rs # CLI 处理
│ ├── config.rs # 配置管理
│ ├── error.rs # 错误类型
│ └── utils.rs # 工具函数
├── tests/ # 集成测试
│ └── integration_test.rs
└── target/ # 编译输出(.gitignore)
添加依赖
bash
# 命令行参数解析
cargo add clap
# 错误处理
cargo add anyhow
# 日志
cargo add env_logger
常用命令速查
| 命令 | 说明 |
|---|---|
cargo new project |
创建新项目 |
cargo build |
编译(debug) |
cargo build --release |
编译(release) |
cargo run |
编译并运行 |
cargo run -- show |
运行并传参 |
cargo test |
运行测试 |
cargo check |
快速检查(不生成二进制) |
cargo clean |
清理编译产物 |
cargo install --path . |
安装到系统 |
cargo update |
更新依赖 |
跨平台编译
Windows 编译 Linux
bash
rustup target add x86_64-unknown-linux-gnu
cargo build --release --target x86_64-unknown-linux-gnu
macOS 编译 Windows
bash
rustup target add x86_64-pc-windows-gnu
cargo build --release --target x86_64-pc-windows-gnu
发布到 crates.io
bash
# 1. 注册账号
cargo login
# 2. 检查包名是否可用
cargo search anthropic-config
# 3. 发布
cargo publish
故障排查
问题:找不到命令
bash
# 检查 PATH
echo $PATH # Linux/macOS
echo %PATH% # Windows
# 检查安装位置
which anthropic-config # Linux/macOS
where anthropic-config # Windows
问题:编译失败
bash
# 清理后重新编译
cargo clean
cargo build
问题:权限错误
bash
# Linux/macOS 确保可执行
chmod +x target/release/anthropic-config
参考资源
总结
构建 Rust CLI 项目的关键步骤:
- 使用
cargo new创建标准结构 - 按功能拆分模块(cli, handlers, env, utils)
- 使用
cargo build --release优化编译 - 使用
cargo install --path .安装到系统 - 确保
~/.cargo/bin在 PATH 中
这种结构便于维护、测试和发布,感兴趣的小伙伴可以看一下项目源码