clap-nested-commands
Rust macros to automate the command definitions for nested commands in a clap
CLI.
Installation
Add clap-nested-commands
to your project's Cargo.toml
:
[]
= { = "x.y.z", = ["derive"] }
= "0.*"
Async commands
If your CLI commands are async
, you also need the anyhow
dependency:
[]
= "x.y.z"
= { = "x.y.z", = ["derive"] }
= "0.*"
Usage
For example, imagine a CLI command like my-cli project user add --email name@domain.com
.
With clap-nested-commands
, you structure this CLI as follows:
examples/sync_commands
├── Cargo.toml
├── cli_context.rs
├── src
│ └── commands
│ ├── mod.rs
│ └── project
│ ├── mod.rs
│ ├── task
│ │ ├── add.rs
│ │ ├── mod.rs
│ │ └── remove.rs
│ └── user
│ ├── add.rs
│ ├── mod.rs
│ └── remove.rs
└── main.rs
Sync commands
Use the following pattern in your src/commands/**/mod.rs
files:
// src/commands/project/user
use ;
use generate_sync_commands;
use crate CliContext;
// A list of sub-command modules
/// User commands
generate_sync_commands!;
Individual commands look like this:
// src/commands/project/user/add.rs
use Args;
use crate CliContext;
/// Add a user
Note: If you want to return data from your commands, see the sync_commands_with_return_type
example.
Async commands
The only difference compared to sync commands is the use of the generate_async_commands
macro.
Use the following pattern in your src/commands/**/mod.rs
files:
// src/commands/project/user
use ;
use generate_async_commands;
use crate CliContext;
// A list of sub-command modules
/// User commands
generate_async_commands!;
Individual commands look like this:
// src/commands/project/user/add.rs
use Error;
use Args;
use crate CliContext;
/// Add a user
pub async
Note: If you want to return data from your commands, see the async_commands_with_return_type
example.
Examples
See ./examples
for both a sync and an async example. To run them, use the following commands:
cargo run --example async_commands <sub-commands>
- E.g.
cargo run --example async_commands project user add --email name@domain.com
- E.g.
cargo run --example async_commands_with_return_type <sub-commands>
- E.g.
cargo run --example async_commands_with_return_type project user add --email name@domain.com
- E.g.
cargo run --example sync_commands <sub-commands>
- E.g.
cargo run --example sync_commands project user add --email name@domain.com
- E.g.
cargo run --example sync_commands_with_return_type <sub-commands>
- E.g.
cargo run --example sync_commands_with_return_type project user add --email name@domain.com
- E.g.