rustclap

How to call a function with clap


I want to call a function store_blocklist::insert_blocklist() by using clap

pub fn args() -> Command {
    Command::new("admin-cli")
        .about("CLI to manage admin tasks")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .allow_external_subcommands(false)
        .subcommand(
            Command::new("blocklist")
                .about("Storing the blocklists of SteveBlack in the database")
                //call store_blocklist::insert_blocklist() here
        )
}

How can I do this?


Solution

  • This is not the job of Clap. Clap is a command-line arguments parser, and that's it.

    After Clap processes the user's arguments, you can do whatever you want with them, including calling your function:

    use clap::{Arg, ArgAction, Command};
    
    pub fn args() -> Command {
        Command::new("admin-cli")
            .about("CLI to manage admin tasks")
            .arg_required_else_help(true)
            .allow_external_subcommands(false)
            .arg(
                Arg::new("blocklist")
                    .long("blocklist")
                    .help("Storing the blocklists of SteveBlack in the database")
                    .action(ArgAction::SetTrue),
            )
    }
    
    fn main() {
        let cmd = args();
        let args = cmd.get_matches();
    
        if args.get_flag("blocklist") {
            // Call your function here.
            println!("Hi from blocklist!");
        }
    }