NikBond
NikBond

Reputation: 763

How to use a CLI argument after subcommand with the structopt crate?

For example, running my application with

./app --foo=bar get

works well, but

./app get --foo=bar

Produces an error:

error: Found argument '--foo' which wasn't expected, or isn't valid in this context

USAGE:
    app --foo <foo> get

Code:

use structopt::*;

#[derive(Debug, StructOpt)]
#[structopt(name = "app")]
struct CliArgs {
    #[structopt(long)]
    foo: String,
    #[structopt(subcommand)]
    cmd: Cmd,
}

#[derive(Debug, StructOpt)]
enum Cmd {
    Get,
    Set,
}

fn main() {
    let args = CliArgs::from_args();
    println!("{:?}", args);
}

Dependencies:

structopt = { version = "0.3", features = [ "paw" ] }
paw = "1.0"

Upvotes: 3

Views: 1261

Answers (2)

NikBond
NikBond

Reputation: 763

According to issue 237, there is a global parameter. Unexpectedly, it is not mentioned in the documentation.

With global = true it works well:

use structopt::*;

#[derive(Debug, StructOpt)]
#[structopt(name = "cli")]
struct CliArgs {
    #[structopt(
        long,
        global = true,
        default_value = "")]
    foo: String,
    #[structopt(subcommand)]
    cmd: Cmd,
}

#[derive(Debug, StructOpt)]
enum Cmd {
    Get,
    Set,
}

fn main() {
    let args = CliArgs::from_args();
    println!("{:?}", args);
}

Note that the global argument must be optional or have a default value.

Upvotes: 4

Shepmaster
Shepmaster

Reputation: 431599

You need to provide another struct for each command enum variant that has arguments:

use structopt::*; // 0.3.8

#[derive(Debug, StructOpt)]
struct CliArgs {
    #[structopt(subcommand)]
    cmd: Cmd,
}

#[derive(Debug, StructOpt)]
enum Cmd {
    Get(GetArgs),
    Set,
}

#[derive(Debug, StructOpt)]
struct GetArgs {
    #[structopt(long)]
    foo: String,
}

fn main() {
    let args = CliArgs::from_args();
    println!("{:?}", args);
}
./target/debug/example get --foo=1
CliArgs { cmd: Get(GetArgs { foo: "1" }) }

Upvotes: 0

Related Questions