aboutsummaryrefslogtreecommitdiff
path: root/docs/pages/7-argument-parse-clap.md
blob: e912c38b1b26a721c2f3820e96bc08bca2642e74 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<h1 align="center">Parsing Arguments with Clap</h1>
<p align="center">
    Use clap for more complex argument parsing
</p>

Picker is suitable for lightweight arg extraction, but when there are many args, complex validation rules, or you need auto-generated `--help`, you can use [clap](https://crates.io/crates/clap).

## Enable clap feature

```toml
[dependencies.mingling]
features = ["clap"]
 
[dependencies.clap]
version = "4"
features = ["derive", "color"]
```
 
## dispatcher_clap

Add `#[dispatcher_clap]` on a `clap::Parser` struct to auto-generate a Dispatcher:

```rust
// Features: ["clap"]
// Dependencies:
// clap = "4"
@@@ use mingling::macros::dispatcher_clap;
#[derive(Default, clap::Parser, Groupped)]
#[dispatcher_clap("greet", CMDGreet, help = true, error = ErrorGreetParsed)]
pub struct EntryGreet {
    #[clap(default_value = "World")]
    name: String,
    #[arg(short, long, default_value_t = 1)]
    repeat: i32,
}
 
#[renderer]
fn render_greet(greet: EntryGreet) {
    let count = greet.repeat.max(0) as usize;
    r_print!("Hello, ");
    for _ in 0..count {
        r_print!("{} ", greet.name);
    }
    r_println!("!");
}
 
#[renderer]
fn render_greet_parse_failed(err: ErrorGreetParsed) {
    r_println!("{}", *err);
}
```
 
## Working with BasicProgramSetup

If you need `--help` support, register `BasicProgramSetup` in main and set the clap help output mode:

```rust
// Features: ["clap"]
// Dependencies:
// clap = "4"
@@@use mingling::setup::BasicProgramSetup;
@@@use mingling::macros::dispatcher_clap;
@@@#[derive(Default, clap::Parser, Groupped)]
@@@#[dispatcher_clap("greet", CMDGreet)]
@@@pub struct EntryGreet {
@@@    name: String,
@@@}
@@@#[renderer]
@@@fn render_greet(greet: EntryGreet) {
@@@    r_println!("Hello, {}!", greet.name);
@@@}
@@@
fn main() {
    let mut program = ThisProgram::new();
    program.with_setup(BasicProgramSetup);
    program.stdout_setting.clap_help_print_behaviour =
        mingling::ClapHelpPrintBehaviour::WriteToRenderResult;
    program.with_dispatcher(CMDGreet);
    program.exec_and_exit();
}
```
 
See [example-clap-binding](https://mingling-rs.github.io/mingling/docs/example-viewer.html?name=example-clap-binding) for more details.

<p align="center" style="font-size: 0.85em; color: gray;">
    Written by @Weicao-CatilGrass
</p>