Appearance
Rust 命令行工具
本章节将介绍如何使用 Rust 创建命令行工具。
项目设置
创建项目
bash
cargo new --bin cli-tool
cd cli-tool添加依赖
在 Cargo.toml 文件中添加依赖:
toml
[dependencies]
clap = { version = "4", features = ["derive"] }
colored = "2"基本结构
命令行参数解析
使用 clap 库解析命令行参数:
rust
use clap::Parser;
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// Name of the person to greet
#[arg(short, long)]
name: String,
/// Number of times to greet
#[arg(short, long, default_value_t = 1)]
count: u8,
}
fn main() {
let args = Args::parse();
for _ in 0..args.count {
println!("Hello, {}!", args.name);
}
}子命令
使用 clap 库定义子命令:
rust
use clap::{Parser, Subcommand};
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Greet someone
Greet {
/// Name of the person to greet
name: String,
/// Number of times to greet
#[arg(short, long, default_value_t = 1)]
count: u8,
},
/// Calculate something
Calculate {
/// First number
a: i32,
/// Second number
b: i32,
/// Operation to perform
#[arg(short, long, default_value = "add")]
operation: String,
},
}
fn main() {
let args = Args::parse();
match &args.command {
Commands::Greet { name, count } => {
for _ in 0..*count {
println!("Hello, {}!", name);
}
}
Commands::Calculate { a, b, operation } => {
match operation.as_str() {
"add" => println!("{} + {} = {}", a, b, a + b),
"subtract" => println!("{} - {} = {}", a, b, a - b),
"multiply" => println!("{} * {} = {}", a, b, a * b),
"divide" => {
if *b == 0 {
println!("Error: Cannot divide by zero");
} else {
println!("{} / {} = {}", a, b, a / b);
}
}
_ => println!("Error: Unknown operation"),
}
}
}
}高级功能
配置文件
使用 config 库读取配置文件:
toml
[dependencies]
config = "0.13"
serde = { version = "1", features = ["derive"] }rust
use serde::Deserialize;
use config::Config;
#[derive(Debug, Deserialize)]
struct AppConfig {
default_name: String,
default_count: u8,
}
fn load_config() -> AppConfig {
let config = Config::builder()
.add_source(config::File::with_name("config"))
.build()
.unwrap();
config.try_deserialize().unwrap()
}
fn main() {
let config = load_config();
println!("Default name: {}", config.default_name);
println!("Default count: {}", config.default_count);
}进度条
使用 indicatif 库显示进度条:
toml
[dependencies]
indicatif = "0.17"rust
use indicatif::ProgressBar;
use std::thread;
use std::time::Duration;
fn main() {
let pb = ProgressBar::new(100);
for i in 0..100 {
thread::sleep(Duration::from_millis(50));
pb.inc(1);
}
pb.finish_with_message("Done");
}颜色输出
使用 colored 库输出彩色文本:
rust
use colored::*;
fn main() {
println!("{}", "Success!".green());
println!("{}", "Error!".red());
println!("{}", "Warning!".yellow());
println!("{}", "Info!".blue());
}发布工具
构建发布版本
bash
cargo build --release发布到 Crates.io
登录 Crates.io:
bashcargo login <API_TOKEN>发布 crate:
bashcargo publish
跨平台构建
使用 cross 工具进行跨平台构建:
bash
cargo install cross
cross build --target x86_64-pc-windows-gnu --release
cross build --target x86_64-apple-darwin --release
cross build --target x86_64-unknown-linux-gnu --release总结
- 项目设置:使用
cargo new --bin创建命令行项目 - 命令行参数解析:使用
clap库解析命令行参数 - 子命令:使用
clap库定义子命令 - 配置文件:使用
config库读取配置文件 - 进度条:使用
indicatif库显示进度条 - 颜色输出:使用
colored库输出彩色文本 - 发布工具:构建发布版本并发布到 Crates.io
- 跨平台构建:使用
cross工具进行跨平台构建
通过本章节的学习,你应该已经掌握了使用 Rust 创建命令行工具的方法。