Skip to content

Add support for subcommands #135

@tgross35

Description

@tgross35

It would be nice if we could support subcommands, i.e.

./cli --root-arg a build --arg-for-build foo
./cli --root-arg b run --arg-for-run bar

One API possibility is to use the same Options but allow registering subcommands:

// Root option
let mut opts = Options::new();
opts.optflag("r", "root-arg", "dummy arg before subcommand");

let mut sub_build = Options::new();
sub_build.opts.optopt("a", "arg-for-build", "build argument", "TEXT");
opts.subcommand(sub_build, "b", "build", "start a build");

let mut sub_run = Options::new();
sub_run.opts.optopt("a", "arg-for-run", "build argument", "TEXT");
opts.subcommand(sub_run, "r", "run", "run the program");

Not sure what is best for Matches. The way that python does it is by treating the subcommand as a pseudoflag that you can name (via e.g. dest="subcommand") then merging all options. So the above example would need a call like opts.subcommand_arg_name("sub"), then a flag dump would look like:

{
    "root-arg": "a",
    "sub": "build",
    "arg-for-build": "foo",
}

{
    "root-arg": "b",
    "sub": "run",
    "arg-for-run": "bar",
}

That needs some validation that flags don't conflict, i.e. ./cli -a subcommand -a would be disallowed.

Alternatively, maybe something like:

impl Matches {
    /// If the subcommand was set, return matches for its arguments.
    fn subcommand_matches(&self, name: &str) -> Option<Matches>;
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions