Search code examples
rustcommand-lineclap

Migrating Clap CLI Argument Definitions from Version 2.33.3 to 4.4.2


I recently upgraded Clap from version 2.33.3 to 4.4.2 in my Rust project. In the previous version, I used

matches.occurrences_of("verbosity")

to count the number of times a verbosity flag was provided, and

matches.is_present("silent")

to check if a silent flag was provided. However, it seems that in Clap 4.4.2, the occurrences_of method and the multiple attribute for arguments are no longer available. As a result, my code is not working as expected.

let _verbosity = matches.occurrences_of("verbosity");
let _is_silent = matches.is_present("silent");
// Determine verbosity level and log level based on command line arguments.
let log_level = if _is_silent {
log::LevelFilter::Error
} else if _verbosity <= 1 {
log::LevelFilter::Info
} else if _verbosity == 2 {
log::LevelFilter::Debug
} else {
log::LevelFilter::Trace
};`

and

 let matches = Command::new("backend_snapshot")
.version("1.0")
.subcommand_required(true)
.about("A snapshot uploader and downloader")
.arg(
    Arg::new("verbosity")
        .short('v')
        .num_args(1..)
        .long("verbose")
        .help("Increase verbosity level"),
)
.arg(
    Arg::new("silent")
        .short('s')
        .long("silent")
        .help("Decrease verbosity level, only important info, 
 warnings, errors are written"),
)

How can I achieve the same functionality in Clap 4.4.2 as I did in Clap 2.33.3 regarding counting the occurrences of an argument and checking if an argument is present?

I would appreciate any help or advice on how to adapt my code to work with Clap 4.4.2 or any alternative methods to achieve the same functionality.


Solution

  • From the migration guide:

    arg! now sets one of (#3795):

    • ArgAction::SetTrue, requiring ArgMatches::get_flag instead of ArgMatches::is_present
    • ArgAction::Count, requiring ArgMatches::get_count instead of ArgMatches::occurrences_of