最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rust - can clap somehow handle more than one subcommands group? - Stack Overflow

programmeradmin0浏览0评论

consider this test:

#[test]
fn test_sub_commands(){
    

    let option_0_a_sub_cmd = Command::new("option_0_a")
        .about("does testing things")
        .arg(
            Arg::new("field_a")
                .long("field-a")
                .action(ArgAction::Set)
                .value_parser(clap::value_parser!(u32))
                .required(true)
        );

    let option_0_b_sub_cmd = Command::new("option_0_b")
        .about("does testing things")
        .arg(
            Arg::new("field_b")
                .long("field-b")
                .action(ArgAction::Set)
                .value_parser(clap::value_parser!(u32))
                .required(true)
        );

    let option_1_a_sub_cmd = Command::new("option_1_a")
        .about("does testing things")
        .arg(
            Arg::new("field_a")
                .long("field-a")
                .action(ArgAction::Set)
                .value_parser(clap::value_parser!(u32))
                .required(true)
        );

    let option_1_b_sub_cmd = Command::new("option_1_b")
        .about("does testing things")
        .arg(
            Arg::new("field_b")
                .long("field-b")
                .action(ArgAction::Set)
                .value_parser(clap::value_parser!(u32))
                .required(true)
        );


    let train_cmd = Command::new("test")
        .about("does testing things")
        .arg(
            Arg::new("some_field")
                .long("some-field")
                .action(ArgAction::Set),
        )
        .subcommands(vec![
            option_0_a_sub_cmd,
            option_0_b_sub_cmd,
        ])
        .subcommand_required(true)
        .subcommands(vec![
            option_1_a_sub_cmd,
            option_1_b_sub_cmd,
        ]);


    let matches = train_cmd.get_matches_from(["test_cli", "--some-field", "zzz", "option_0_a", "--field-a", "10", "option_1_b", "--field-b", "20"]);

    
    if let Some(option_a_match) = matches.subcommand_matches("option_0_a") {
        for id in option_a_match.ids() {
            println!("option_a_match: id={:?}", id);
        }
    }
    if let Some(option_b_match) = matches.subcommand_matches("option_1_b") {
        for id in option_b_match.ids() {
            println!("option_b_match: id={:?}", id);
        }
    }
   

}

it fails with

error: unexpected argument 'option_1_b' found

I need to have more than one group of subcommands,so that I could exec option_0_a and option_1_b, but clap doesn't seem to allow this. Is there workaround?

ps - gpt suggested to either nest subommands or use try_get_matches_from_mut and parse each subcommand separately but neither actually works

发布评论

评论列表(0)

  1. 暂无评论