Rust CLI工具开发:从clap到发布
3 阅读
预计 3 分钟
Rust是开发CLI工具的理想语言。本文介绍使用clap构建专业CLI应用。
## 项目初始化
```bash
cargo new mycli
cd mycli
```
```toml
[dependencies]
clap = { version = "4", features = ["derive"] }
```
## 定义CLI参数
```rust
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(name = "mycli")]
#[command(about = "A cool CLI tool", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
#[arg(short, long, global = true)]
verbose: bool,
}
#[derive(Subcommand)]
echo Commands {
Add { name: String },
List { #[arg(short, long)] all: bool },
Remove { id: u32 },
}
fn main() {
let cli = Cli::parse();
match cli.command {
Commands::Add { name } => println!("Adding: {}", name),
Commands::List { all } => println!("Listing (all={})", all),
Commands::Remove { id } => println!("Removing: {}", id),
}
}
```
## 进度条与颜色
```rust
use indicatif::ProgressBar;
use console::style;
let pb = ProgressBar::new(100);
for i in 0..100 {
pb.inc(1);
}
pb.finish();
println!("{}", style("Success!").green().bold());
```
## 交互式输入
```rust
use dialoguer::{Input, Select, Confirm};
let name: String = Input::new()
.with_prompt("Your name")
.interact_text()
.unwrap();
```
Rust CLI工具编译为单个二进制文件,无运行时依赖,分发极其方便。
0 条评论 欢迎参与讨论