3

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"
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
NikBond
  • 743
  • 1
  • 5
  • 20

2 Answers2

4

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.

NikBond
  • 743
  • 1
  • 5
  • 20
  • `global` is not mentioned in the documentation because it is a clap feature. But it is documented that `#[structopt(...)]` supports clap methods. – Carlos Marx Aug 21 '21 at 01:04
0

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" }) }
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366