Convert flag to optional option #5598
-
Hi! I have this simple clap Parser: #[derive(Debug, Parser)]
pub struct Cli {
#[arg(short, long)]
install: bool,
repo: String,
} which you can run like $ cargo run -- any_repo
# Args: Cli { install: false, repo: "any_repo" }
$ cargo run -- --install any_repo
# Args: Cli { install: true, repo: "any_repo" } Now I need to convert the flag to an optional option: #[derive(Debug, Parser)]
pub struct Cli {
#[arg(short, long)]
install: Option<Option<String>>,
repo: String,
} But running the last example command, it doesn't work anymore: $ cargo run -- --install any_repo
error: the following required arguments were not provided:
<REPO>
Usage: clap-flag-to-option --install [<INSTALL>] <REPO>
For more information, try '--help'
Here, the value The only way to make it work is to run In this situation, do you have any advice on possible solutions? The two solution I see are:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Yes, this is implicitly a One option not covered there is to use require_equals = true #!/usr/bin/env nargo
---
[dependencies]
clap = { path = "../clap", features =["derive"] }
---
use clap::Parser;
#[derive(Debug, Parser)]
pub struct Cli {
#[arg(short, long, require_equals = true)]
install: Option<Option<String>>,
repo: String,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
} $ ./clap-5598.rs --install a
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s
Running `/home/epage/src/personal/cargo/target/debug/cargo -Zscript ./clap-5598.rs --install a`
warning: `package.edition` is unspecified, defaulting to `2021`
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s
Running `/home/epage/.cargo/target/38/fa72cbe0999338/debug/clap-5598 --install a`
Cli { install: Some(None), repo: "a" } $ ./clap-5598.rs --install=b a
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s
Running `/home/epage/src/personal/cargo/target/debug/cargo -Zscript ./clap-5598.rs --install=b a`
warning: `package.edition` is unspecified, defaulting to `2021`
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s
Running `/home/epage/.cargo/target/38/fa72cbe0999338/debug/clap-5598 --install=b a`
Cli { install: Some(Some("b")), repo: "a" } |
Beta Was this translation helpful? Give feedback.
Yes, this is implicitly a
num_args(0..=1)
which comes with a big warning in the docs.One option not covered there is to use require_equals = true