rust 编程访问Clap Derive Arg属性特性

enxuqcxy  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(147)

给定一个定义如下的struct:

use clap::Parser;
use validator::Validate;

#[derive(Parser, Debug, Validate)]
#[command(author="", version="0.0.1", about="Utility to split files", long_about = None)]
pub struct TestArgs {

    #[arg(short, long, required = true, help="Specify a local file or folder for processing.\nFolders will attempt to process all files in the folder")]
    #[validate(custom = "crate::cli::validation::validate_input")]
    pub input: String,

    #[arg(short, long, help="This is the location to which processed files are moved.\nDefault value \"\" will be processed as [PWD]/output.", required = false, default_value="")]
    #[validate(custom = "crate::cli::validation::validate_outfolder")]
    pub out_folder: String
}

然后在main中解析如下:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let args = TestArgs::parse();

    match args.validate() {
        Ok(_) => (),
        Err(e) => {
            println!();
            eprintln!("{}", e.to_string());
            println!();
            process::exit(1);
        }
    };
.
.
}

如何以编程方式访问arg[]属性中声明的各个属性值的每个参数?
我发现了一些使用clap::Clap的例子,比如:

let arg_parser = TestArgs.into_app();

然后通过arg_parser变量进行访问。但是,Clap 4.2.1似乎不支持这种方式。
如果有人知道如何或有如何访问这些值的想法,这将是非常有帮助的。

byqmnocz

byqmnocz1#

您可以通过调用CommandFactory trait提供的command()来访问从您的属性生成的Command

use clap::{CommandFactory, Parser};

#[derive(Parser, Debug)]
#[command(author="", version="0.0.1", about="Utility to split files", long_about = None)]
pub struct TestArgs {
    #[arg(short, long, required = true, help="Specify a local file or folder for processing.\nFolders will attempt to process all files in the folder")]
    pub input: String,

    #[arg(short, long, help="This is the location to which processed files are moved.\nDefault value \"\" will be processed as [PWD]/output.", required = false, default_value="")]
    pub out_folder: String
}

fn main() {
    let command = TestArgs::command();
}

然后,您可以通过各种get_*is_*Command及其Arg上的其他方法访问所有内容。

相关问题