|
| 1 | +# CommandContext |
| 2 | + |
| 3 | +Every command handler receives a `&CommandContext` as its only argument. It contains everything |
| 4 | +vecli parsed from the command line for that invocation. |
| 5 | + |
| 6 | +```rust |
| 7 | +fn my_command(ctx: &CommandContext) { |
| 8 | + // ctx is yours to use |
| 9 | +} |
| 10 | +``` |
| 11 | + |
| 12 | +## Fields |
| 13 | + |
| 14 | +### `ctx.subcommand` |
| 15 | + |
| 16 | +The name of the command as typed by the user, e.g. `"add"` or `"list"`. |
| 17 | + |
| 18 | +```rust |
| 19 | +println!("Running: {}", ctx.subcommand); |
| 20 | +``` |
| 21 | + |
| 22 | +### `ctx.positionals` |
| 23 | + |
| 24 | +A `Vec<String>` of all non-flag tokens that followed the subcommand, in order. |
| 25 | + |
| 26 | +```sh |
| 27 | +mytool add "buy milk" groceries |
| 28 | +# ctx.positionals == ["buy milk", "groceries"] |
| 29 | +``` |
| 30 | + |
| 31 | +```rust |
| 32 | +let task = ctx.positionals.first().map(String::as_str).unwrap_or("unnamed"); |
| 33 | +``` |
| 34 | + |
| 35 | +### `ctx.flags` |
| 36 | + |
| 37 | +A `HashMap<String, String>` of all flags passed by the user, keyed by canonical name after alias |
| 38 | +resolution. Boolean flags (no explicit value) have the value `"true"`. |
| 39 | + |
| 40 | +```sh |
| 41 | +mytool add "buy milk" --priority high -v |
| 42 | +# ctx.flags == { "priority": "high", "verbose": "true" } |
| 43 | +``` |
| 44 | + |
| 45 | +```rust |
| 46 | +if ctx.flags.contains_key("verbose") { |
| 47 | + println!("verbose mode"); |
| 48 | +} |
| 49 | + |
| 50 | +let priority = ctx.flags.get("priority").map(String::as_str).unwrap_or("medium"); |
| 51 | +``` |
| 52 | + |
| 53 | +Global flags registered on the app are merged in automatically — no extra setup needed in the handler. |
| 54 | + |
| 55 | +## Full Example |
| 56 | + |
| 57 | +```rust |
| 58 | +fn add(ctx: &CommandContext) { |
| 59 | + let task = ctx.positionals.first().map(String::as_str).unwrap_or("unnamed"); |
| 60 | + let priority = ctx.flags.get("priority").map(String::as_str).unwrap_or("medium"); |
| 61 | + |
| 62 | + if ctx.flags.contains_key("verbose") { |
| 63 | + println!( |
| 64 | + "[verbose] subcommand='{}', positionals={:?}, flags={:?}", |
| 65 | + ctx.subcommand, ctx.positionals, ctx.flags |
| 66 | + ); |
| 67 | + } |
| 68 | + |
| 69 | + println!("Added '{}' with priority {}.", task, priority); |
| 70 | +} |
| 71 | +``` |
| 72 | + |
| 73 | +--- |
| 74 | + |
| 75 | +If you've been this far from the beginning, congrats! This doc is under production and you've reached the end... for now. More guides will be added soon! For now, read the API reference at [docs.rs](https://docs.rs/vecli). |
0 commit comments