diff options
| author | 魏曹先生 <1992414357@qq.com> | 2026-04-06 20:19:43 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2026-04-06 20:19:43 +0800 |
| commit | 721b6f9f608977b938dbc9b847c9221370b5ee15 (patch) | |
| tree | 95483051d50d183357a097c41a678bad14c657c0 /examples/example-picker/src/main.rs | |
| parent | e68e1230d4157c32592900372699411c7151b4e5 (diff) | |
Add workspace configuration and examples
Diffstat (limited to 'examples/example-picker/src/main.rs')
| -rw-r--r-- | examples/example-picker/src/main.rs | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/examples/example-picker/src/main.rs b/examples/example-picker/src/main.rs new file mode 100644 index 0000000..24357a8 --- /dev/null +++ b/examples/example-picker/src/main.rs @@ -0,0 +1,68 @@ +//! `Mingling` Example - Picker +//! +//! ## Step1 - Enable Feature +//! Enable the `parser` feature for mingling in `Cargo.toml` +//! ```toml +//! [dependencies] +//! mingling = { version = "...", features = ["parser"] } +//! ``` +//! +//! ## Step2 - Write Code +//! Write the following content into `main.rs` +//! +//! ## Step3 - Build and Run +//! ```bash +//! cargo run --manifest-path ./examples/example-picker/Cargo.toml -- pick Bob +//! cargo run --manifest-path ./examples/example-picker/Cargo.toml -- pick Bob --age -15 +//! cargo run --manifest-path ./examples/example-picker/Cargo.toml -- pick --age 99 +//! ``` + +use mingling::{ + AnyOutput, + macros::{chain, dispatcher, gen_program, pack, r_println, renderer}, + marker::NextProcess, + parser::Picker, +}; + +dispatcher!("pick", PickCommand => PickEntry); + +#[tokio::main] +async fn main() { + let mut program = DefaultProgram::new(); + program.with_dispatcher(PickCommand); + program.exec().await; +} + +pack!(NoNameProvided = ()); +pack!(ParsedPickInput = (i32, String)); + +#[chain] +async fn parse(prev: PickEntry) -> NextProcess { + // Extract arguments from `PickEntry`'s inner and create a `Picker` + let picker = Picker::new(prev.inner); + let picked = picker + // First extract the named argument + .pick_or("--age", 20) + .after(|n: i32| n.clamp(0, 100)) + // Then sequentially extract the remaining arguments + .pick_or_route((), AnyOutput::new(NoNameProvided::default())) + .unpack(); + + match picked { + Ok(value) => ParsedPickInput::new(value).to_render(), + Err(e) => e.route_renderer(), + } +} + +#[renderer] +fn render_parsed_pick_input(prev: ParsedPickInput) { + let (age, name) = prev.inner; + r_println!("Picked: name = {}, age = {}", name, age); +} + +#[renderer] +fn render_no_name_input(_prev: NoNameProvided) { + r_println!("No name provided."); +} + +gen_program!(); |
