0

Given a struct defined as follows:

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
}

Which is then parsed in main as follows:

#[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);
        }
    };
.
.
}

How can the individual properties values declared in the arg[] attribute be programmatically accessed for each argument?

I've found some examples using clap::Clap to do something like:

let arg_parser = TestArgs.into_app();

and then access through the arg_parser variable. However, that doesn't seem to be something that is supported in Clap 4.2.1.

If someone knows how or has an idea of how to access those values, it would be extremely helpful.

jrf
  • 41
  • 4

1 Answers1

1

You can access the Command generated from your attributes by calling command() provided by the CommandFactory trait:

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();
}

You can then access everything via the various get_*, is_*, and other methods on the Command and its Args.

kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • Thanks @kmdreko! I'll take a look at that today. I'm new to Rust and Clap. So, I have a learning to do on everything, but I'm especially trying to get a fluid understanding of the various ways to use Clap. I haven't done anything with the `get_*` and `is_*` methods yet and I'll give that a go. – jrf Apr 19 '23 at 13:33