If you want the string argument to come before the command2 (i.e., the structure should be):
mycli <arg> command2
rather than:
mycli command2 <arg>
Then this is a bit non-standard for clap, because subcommands usually encapsulate their arguments. However, you can achieve this by using a flat structure, where both the string and the command are top-level optional choices.
✅ Goal
Support these usages:
mycli command1 # runs command1
mycli some-string command2 # runs command2 with "some-string"
📦 Cargo.toml
Make sure you're using clap with the derive feature:
[dependencies]
clap = { version = "4.0", features = ["derive"] }
✅ Solution Using Parser with Custom Logic
Here's how you can do it:
use clap::{Parser, Command, Subcommand};
#[derive(Parser)]
#[clap(name = "mycli")]
#[clap(about = "CLI where string comes before command2")]
struct Cli {
/// Optional string argument (used only for command2)
maybe_string: Option<String>,
#[clap(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand)]
enum Commands {
/// Run command1
Command1,
/// Run command2 (requires a preceding string)
Command2,
}
fn main() {
let cli = Cli::parse();
match (&cli.maybe_string, &cli.command) {
// Handle: mycli some-string command2
(Some(arg), Some(Commands::Command2)) => {
println!("Running command2 with argument: {}", arg);
}
// Handle: mycli command1
(None, Some(Commands::Command1)) => {
println!("Running command1");
}
// Invalid cases
(Some(_), Some(Commands::Command1)) => {
eprintln!("Error: unexpected string before command1");
std::process::exit(1);
}
(None, Some(Commands::Command2)) => {
eprintln!("Error: missing string before command2");
std::process::exit(1);
}
_ => {
eprintln!("Error: no command provided");
std::process::exit(1);
}
}
}
✅ Example Usage
$ mycli command1
Running command1
$ mycli hello command2
Running command2 with argument: hello
❌ Invalid Usages
$ mycli hello command1
Error: unexpected string before command1
$ mycli command2
Error: missing string before command2