rust clap cli basics

 

Clap have the concept of 

a) argument - is input pass to the executing command  for example myexec helloworld. 

helloworld here is the argument

b) options - predefined argument that the program accept, for example myexec -n test 

You will see example below 

When you work with clap derive mode, you have to create a struct that derived from Parser as shown below:

Simple Argument

Here we will create a command line that takes in a string as input 


use std::path::PathBuf;
use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(version, about, long_about = None)]
pub struct Cli {
    pub name: Option<String>,
}

main.rs


fn main() {
    use clap::Parser;
    let cli = cmd::Cli::parse();

    let cli = cmd::Cli::parse();

    println!("name: {:?}", cli.name.as_deref());
}

To execute, run myexec test and it will output 

name: test


Adding argument

If you change your cli struct and add #[arg(short, long), you are creating argument. 

pub struct Cli {
   
    #[arg(short, long)]
    pub name: Option<String>,
}

Then you are saying creating an option. An option require you to specify input like --n (in the example above)

If you would like to specify a short and long option, you can do so using the following code 


pub struct Cli {
    #[arg(short = 'h', long = "hostname")]
    pub hostname: Option<String>,
}

So instead of using -n you get to use -h. This is handy especially when there's a clash with existing automatically infer option such as -h ( --help). 



Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm