rustclap

Add optional to clap rust?


I have working code, but not sure is this correct way to implement it.
CLi program will accept 4 argument, there can be present zero, all or any combination in between.

This is working code:

#[derive(Parser, Default, Debug)]
struct Arguments {
    #[clap(short, long, default_value_t = false)]
    /// if areas.csv to download
    areas: bool,
    #[clap(short, long, default_value_t = false)]
    /// if markers.csv to download
    markers: bool,
    #[clap(short, long, default_value_t = false)]
    /// if tracks.csv to download
    tracks: bool,
    #[clap(short, long)]
    /// path to file of GPS tracks to download
    gpx_list_file: Option<String>,
}

what I do not like is that in -h section there is no way to know that they are optional.

Options:
-a, --areas                          if areas.csv to download
-m, --markers                        if markers.csv to download
-t, --tracks                         if tracks.csv to download
-g, --gpx-list-file <GPX_LIST_FILE>  path to file of GPS tracks to download
-h, --help                           Print help information
-V, --version                        Print version information

I know that I could add text like "This is optional field", but I have feeling that there is better way.

Also what is best way to know if I have 0 argument.
Currently I use this.

    if (args.areas, args.markers, args.tracks, args.gpx_list_file.is_none()) == (false, false, false, true) {
        println!("Nothing to download.");
        exit(5);
}

Solution

  • It's perhaps a bit confusing. When a named argument is optional, you don't see anything telling you that specifically; you just get something like this:

    Usage: command [OPTIONS]
    
    Options:
      -a, --areas            if areas.csv to download
      -n, --number <NUMBER>  [default: 1]
      -h, --help             Print help information
      -V, --version          Print version information
    

    When --areas is required, the help output now includes --areas in the "Usage:" line:

    Usage: command [OPTIONS] --areas
    
    Options:
      -a, --areas            if areas.csv to download
      -n, --number <NUMBER>  [default: 1]
      -h, --help             Print help information
      -V, --version          Print version information
    

    The presence of --areas in the Usage section lets you know it's required, and its absence tells you it's optional.