I found a link for what i want here: Parse user input String with clap for command line programming But it's not completely clear. I see lots of post using App::new() but i can't find any trace of it in clap documentation.
I want to parse a string inside my rust application (it doesn't come from the cmdline) Currently i'm doing it like this:
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
/// Optional name to operate on
test: String,
name: Option<String>,
}
pub fn test(mut to_parse: &String) {
let Ok(r) = shellwords::split(to_parse) else {
info!("error during process");
return;
};
let test = Cli::parse_from(r);
if let Some(name) = test.name.as_deref() {
println!("Value for name: {}", name);
}
}
And it kind of work, but maybe i don't understand enough how clap work. It only take positional argument like --test or --name. there must be a way to have a command before argument?
And the other question i have is : if i'm using a struct to define a command and use Cli::parse_from()
to parse my string, how do i parse my string with multiple command (maybe unclear, but how do i use multiple commands?)
------EDIT I've played with clap a little, and now i've something like this:
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Com,
}
/// Doc comment
#[derive(Subcommand)]
enum Com {
/// First command
Test(TestArg),
///Second command
SecondTest(OtherArg),
}
#[derive(Args)]
struct TestArg {
name: String,
}
#[derive(Args)]
struct OtherArg {
name: Option<String>,
and: Option<String>,
}
Nevertheless, when i enter a command in my in-game console (still parse with parse_from
), nothing is recognize, i always have the error message.