PrivateRookie

PrivateRookie

多少事,从来急.天地转,光阴迫.

2023-05-11-HowTo-clap

HowTo series aims to provide solutions to common engineering problems, including sample code. The theme of this issue is the command line parsing tool clap.

Adding Dependencies#

cargo add clap -F derive -F env

Reading Parameter Values from Environment Variables#

Using the env attribute allows clap to attempt to read from environment variables.

use clap::Parser;

#[derive(Parser)]
struct Cmd {
    #[arg(env="USER")]
    user: String,
}

fn main() {
    let cmd = Cmd::parse();
    println!("user: {}", cmd.user);
}
echo $USER
rookie
cargo run
user: rookie
# The value passed from the command line will override the value from the environment variable
cargo run -- xd
user: xd

Validating Parameters/Converting#

A common scenario is to validate the existence of a path when it is passed as a parameter.

use std::path::PathBuf;

use clap::Parser;

#[derive(Parser)]
struct Cmd {
    #[arg(value_parser=ensure_file)]
    file: PathBuf,
}

fn ensure_file(path: &str) -> Result<PathBuf, String> {
    let path = PathBuf::from(path);
    if path.exists() {
        Ok(path)
    } else {
        Err("file not exists".into())
    }
}

fn main() {
    let cmd = Cmd::parse();
    dbg!(cmd.file);
}
cargo run -- Cargo.toml
[src/main.rs:22] cmd.file = "Cargo.toml"
# Error when the file does not exist
cargo run -- Cargo.tomx
error: invalid value 'Cargo.tomx' for '<FILE>': file not exists

Alternatively, you can directly read the path and deserialize it into a specific type, which is very useful when reading configuration files.

cargo add serde -F derive
cargo add toml
use std::fs::read_to_string;

use clap::Parser;
use serde::Deserialize;

#[derive(Parser)]
struct Cmd {
    #[arg(value_parser=load_conf)]
    conf: Config,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Config {
    pub name: String,
}

fn load_conf(path: &str) -> Result<Config, String> {
    let s = read_to_string(path).map_err(|e| e.to_string())?;
    toml::from_str(&s).map_err(|e| e.to_string())
}

fn main() {
    let cmd = Cmd::parse();
    dbg!(cmd.conf);
}
echo 'name = "rookie"' > demo.toml
cargo run -- demo.toml
[src/main.rs:24] cmd.conf = Config {
    name: "rookie",
}
cargo run -- demo.tomx
error: invalid value 'demo.tomx' for '<CONF>': No such file or directory (os error 2)

Automatic Expansion#

When creating a program with multiple subcommands, different subcommands often share certain parameters. These parameters can be placed in the same structure for easy management. With the help of the #[command(flatten)] attribute, the corresponding command line parameters can be automatically expanded during parsing.

use std::path::PathBuf;

use clap::Parser;

#[derive(Debug, Parser)]
enum Cmd {
    Fetch(FetchCmd),
    Search(SearchCmd),
}

#[derive(Debug, Parser)]
struct FetchCmd {
    name: String,
    #[command(flatten)]
    fmt: FmtOptions,
}
#[derive(Debug, Parser)]
struct SearchCmd {
    pattern: String,
    limit: u64,
    offset: u64,
    #[command(flatten)]
    fmt: FmtOptions,
}

#[derive(Debug, Parser)]
struct FmtOptions {
    #[arg(short, long)]
    format: String,
    #[arg(short, long)]
    wide: u64,
    #[arg(short, long)]
    output: PathBuf,
}

fn main() {
    let cmd = Cmd::parse();
    dbg!(cmd);
}
cargo run -- fetch -h
Usage: demo fetch --format <FORMAT> --wide <WIDE> --output <OUTPUT> <NAME>

Arguments:
  <NAME>  

Options:
  -f, --format <FORMAT>  
  -w, --wide <WIDE>      
  -o, --output <OUTPUT>  
  -h, --help

cargo run -- search -h
Usage: demo search --format <FORMAT> --wide <WIDE> --output <OUTPUT> <PATTERN> <LIMIT> <OFFSET>

Arguments:
  <PATTERN>  
  <LIMIT>    
  <OFFSET>   

Options:
  -f, --format <FORMAT>  
  -w, --wide <WIDE>      
  -o, --output <OUTPUT>  
  -h, --help             Print help

Parsing Enum Values#

Enums are very useful when representing finite options. clap provides the ValueEnum macro, which simplifies enum parsing.

use clap::{Parser, ValueEnum};

#[derive(Debug, Parser)]
struct Cmd {
    color: Color,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum Color {
    Red,
    Green,
    Blue,
}

fn main() {
    let cmd = Cmd::parse();
    dbg!(cmd);
}
cargo run -- -h
Usage: demo <COLOR>

Arguments:
  <COLOR>  [possible values: red, green, blue]

Options:
  -h, --help  Print help
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.