Rust语言

关注公众号 jb51net

关闭
首页 > 软件编程 > Rust语言 > Rust CLI 项目构建

Rust CLI 项目构建的实现步骤

作者:九月生

本文提供了一个完整的Rust CLI项目构建流程,以 anthropic-config 配置管理工具为例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

本文档介绍如何从零开始构建一个标准化的 Rust CLI 项目,以 anthropic-config 工具为例。

项目概述

anthropic-config 是一个用于管理 Anthropic API 配置的 CLI 工具,支持:

完整构建流程

1. 创建项目结构

# 在工作目录下创建新项目
cargo new anthropic-config
cd anthropic-config

生成的标准目录结构:

anthropic-config/
├── Cargo.toml       # 项目配置文件
└── src/
    └── main.rs      # 程序入口

2. 配置 Cargo.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 - 入口点

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 - 命令行解析

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 - 业务逻辑

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 - 环境变量管理

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 - 工具函数

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. 编译和测试

# 开发版本编译(快速,未优化)
cargo build

# 发布版本编译(优化,体积小)
cargo build --release

# 运行测试
cargo test

# 直接运行
cargo run -- show

5. 安装到系统

方法 1: Cargo Install(推荐)

# 从本地路径安装
cargo install --path .

# 更新时重新安装
cargo install --path . --force

安装位置:

原理:

  1. 执行 cargo build --release 编译
  2. 复制 target/release/anthropic-config~/.cargo/bin/
  3. 该目录已在 PATH 中,可直接调用

方法 2: 手动复制

# 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:

# 添加到系统环境变量
$env:Path += ";C:\Users\YourName\.cargo\bin"

# 或通过 GUI 设置
# 系统属性 > 高级 > 环境变量 > Path > 新建

macOS/Linux:

# 添加到 ~/.bashrc 或 ~/.zshrc
export PATH="$HOME/.cargo/bin:$PATH"

# 重新加载配置
source ~/.bashrc

7. 使用工具

# 查看帮助
anthropic-config

# 查看当前配置
anthropic-config show

# 自定义配置
anthropic-config custom

# 使用智谱 AI Big Model
anthropic-config big_model

开发工作流

日常开发流程

# 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)

添加依赖

# 命令行参数解析
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

rustup target add x86_64-unknown-linux-gnu
cargo build --release --target x86_64-unknown-linux-gnu

macOS 编译 Windows

rustup target add x86_64-pc-windows-gnu
cargo build --release --target x86_64-pc-windows-gnu

发布到 crates.io

# 1. 注册账号
cargo login

# 2. 检查包名是否可用
cargo search anthropic-config

# 3. 发布
cargo publish

故障排查

问题:找不到命令

# 检查 PATH
echo $PATH  # Linux/macOS
echo %PATH% # Windows

# 检查安装位置
which anthropic-config  # Linux/macOS
where anthropic-config  # Windows

问题:编译失败

# 清理后重新编译
cargo clean
cargo build

问题:权限错误

# Linux/macOS 确保可执行
chmod +x target/release/anthropic-config

参考资源

总结

构建 Rust CLI 项目的关键步骤:

  1. 使用 cargo new 创建标准结构
  2. 按功能拆分模块(cli, handlers, env, utils)
  3. 使用 cargo build --release 优化编译
  4. 使用 cargo install --path . 安装到系统
  5. 确保 ~/.cargo/bin 在 PATH 中

到此这篇关于Rust CLI 项目构建的实现步骤的文章就介绍到这了,更多相关Rust CLI 项目构建内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文