From f5cdf5cc7c3bd434ff7a88c73b33f96c4d3b6562 Mon Sep 17 00:00:00 2001 From: Weicao-CatilGrass <1992414357@qq.com> Date: Sat, 9 May 2026 14:31:42 +0800 Subject: Add CI tooling and cargo alias `ci` --- docs/pages/3-parsing-complex-arguments.md | 90 +++++++++++++++---------------- 1 file changed, 45 insertions(+), 45 deletions(-) (limited to 'docs/pages/3-parsing-complex-arguments.md') diff --git a/docs/pages/3-parsing-complex-arguments.md b/docs/pages/3-parsing-complex-arguments.md index 8cd5503..b48b28b 100644 --- a/docs/pages/3-parsing-complex-arguments.md +++ b/docs/pages/3-parsing-complex-arguments.md @@ -12,7 +12,7 @@ ```rust let name = args.first().cloned().unwrap_or_else(|| "World".to_string()); ``` - + This chapter introduces a new **Mingling** feature: `Picker`. It provides a lightweight parsing solution that meshes well with **Mingling**'s typed routing. To enable `Picker`, edit `Cargo.toml` ✏️ @@ -24,7 +24,7 @@ mingling = { features = ["parser"] } ``` - + Enough talk, let's get coding and rewrite the parsing logic from the prev. section ✏️ ```rust @@ -33,14 +33,14 @@ fn handle_greet_entry(prev: GreetEntry) -> NextProcess { // Prev. approach: // let args = prev.inner; // let name = args.first().cloned().unwrap_or_else(|| "World".to_string()); - + // New approach with Picker let name = prev.pick_or((), "World").unpack(); - + ResultGreetSomeone::new(name) } ``` - + `Picker` implements `pick`, `pick_or`, and `pick_or_route` for anything `Into>`. These functions let you semantically **pick** args from a string list and convert them into structured data. In the code above: @@ -48,7 +48,7 @@ fn handle_greet_entry(prev: GreetEntry) -> NextProcess { ```rust prev.pick_or((), "World").unpack(); ``` - + Its meaning: ```rust @@ -60,7 +60,7 @@ prev.pick_or((), "World").unpack(); // | |______________________ pick or use default // |___________________________ from the prev. input ``` - + ## Parsing Flag Args If your app needs to parse flag args (e.g., `greet --name Alice`), do: @@ -68,7 +68,7 @@ prev.pick_or((), "World").unpack(); ```rust prev.pick_or(["--name", "-n"], "World").unpack(); ``` - + Its meaning: ```rust @@ -80,7 +80,7 @@ prev.pick_or(["--name", "-n"], "World").unpack(); // | |____________________________________ pick or use default // |_________________________________________ from the prev. input ``` - + ## About `.unpack()` 💡 You may have noticed `Picker` calls `.unpack()` at the end of parsing. It converts the parsed result into structured info. @@ -94,10 +94,10 @@ let (name, age, id) = prev .pick::(["--age", "-a"]) .pick::(["--id", "-I"]) .unpack(); - + // Parses: --name Alice --age 21 --id 0711251 ``` - + > [!IMPORTANT] > `Picker` is very order-sensitive, esp. with positional args: it parses sequentially. > @@ -113,10 +113,10 @@ let (name, age, id) = prev ```rust dispatcher!("greet", GreetCommand => GreetEntry); - + pack!(ResultGreetSomeone = String); pack!(ErrorGreetNoNameProvided = ()); - + #[chain] fn handle_greet_entry(prev: GreetEntry) -> NextProcess { // Use `pick_or_route` to extract the `--name` arg @@ -128,39 +128,39 @@ fn handle_greet_entry(prev: GreetEntry) -> NextProcess { ) // After using any routable method, `unpack` returns `Result` .unpack(); - + // Use the `route!` macro to expand `pick_result`, // If it's `Err`, the chain returns here, routing to the specified type let name = route!(pick_result); ResultGreetSomeone::new(name).to_chain() } - + // Handles rendering for `ErrorGreetNoNameProvided` #[renderer] fn render_err_greet_no_name_provided(_prev: ErrorGreetNoNameProvided) { r_println!("Error: No name provided.") } - + #[renderer] fn render_greet_someone(prev: ResultGreetSomeone) { r_println!("Hello, {}!", *prev); } ``` - + Using `pick_or_route` makes the code a bit more complex: `.unpack()` no longer returns the value directly, but `Result`. However, **Mingling** provides the `route!` macro to simplify expansion. It's not complex—just cuts some boilerplate: ```rust let name = route!(pick_result); - + // Expands to let name = match pick_result { Ok(r) => r, Err(e) => return e, }; ``` - + ## Post-Processing Extracted Values After using `pick` to extract user input, you can use `after` or `after_or_route` to process the arg immediately ✏️ @@ -178,19 +178,19 @@ fn handle_greet_entry(prev: GreetEntry) -> NextProcess { .to_string() }) .unpack(); - + ResultGreetSomeone::new(name) // name is now formatted } ``` - + Similarly, use `after_or_route` to handle format errors in input args ✏️ ```rust dispatcher!("greet", GreetCommand => GreetEntry); - + pack!(ResultGreetSomeone = String); pack!(ErrorGreetNameTooLong = usize); - + #[chain] fn handle_greet_entry(prev: GreetEntry) -> NextProcess { let pick_result = prev @@ -201,7 +201,7 @@ fn handle_greet_entry(prev: GreetEntry) -> NextProcess { .to_lowercase() .trim() .to_string(); - + // Check name length, route to error type if too long let len = name.len(); if len < 32 { @@ -212,22 +212,22 @@ fn handle_greet_entry(prev: GreetEntry) -> NextProcess { }) .unpack(); let name = route!(pick_result); - + ResultGreetSomeone::new(name).to_chain() } - + #[renderer] fn render_error_greet_name_too_long(prev: ErrorGreetNameTooLong) { let len = *prev; r_println!("Error: name too long (length: {} > 32)", len); } - + #[renderer] fn render_greet_someone(prev: ResultGreetSomeone) { r_println!("Hello, {}!", *prev); } ``` - + ## Parsing Booleans `Picker` can parse **bool** types too, but with both explicit and implicit modes: @@ -247,11 +247,11 @@ fn render_greet_someone(prev: ResultGreetSomeone) { fn handle_some_entry(prev: SomeEntry) -> NextProcess { let confirmed: bool = prev.pick::(()).unpack().is_yes(); let confirm: bool = prev.pick::(["--confirm", "-C"]).unpack(); - + // other logic } ``` - + ## Special Use: `usize` Parsing **Mingling** has a special use for `usize`: parsing strings like `25G`, `32mb`, etc. ✏️ @@ -264,7 +264,7 @@ fn parse_size() { assert_eq!(size, 25 * 1024 * 1024); } ``` - + ## Custom Parsable Types Use the `Pickable` trait to make your types parsable by `Picker`. This is where `Picker`'s extensibility comes from ✏️ @@ -276,50 +276,50 @@ pub struct Address { ip: String, port: u16, } - + impl Pickable for Address { type Output = Self; fn pick(args: &mut Argument, flag: Flag) -> Option { // Extract raw string from Argument using Flag let raw = args.pick_argument(flag)?; - + // Parse raw string into structured data let parts: Vec<&str> = raw.split(':').collect(); let ip = parts.first()?.to_string(); let port: u16 = parts.get(1)?.parse().ok()?; - + Some(Address { ip, port }) } } ``` - + With `Pickable` implemented for `Address`, we can now use `ip:port` format for input ✏️ ```rust dispatcher!("connect", ConnectCommand => ConnectEntry); - + pack!(ResultConnected = Address); - + #[chain] fn handle_connect_entry(prev: ConnectEntry) -> NextProcess { let address: Address = prev.pick("--addr").unpack(); ResultConnected::new(address) } - + #[renderer] fn render_connected(prev: ResultConnected) { let addr = prev.inner; r_println!("Connected: IP: {} PORT: {}", addr.ip, addr.port); } ``` - + Running it: ```bash ~> your-bin connect --addr 127.0.0.1:8080 Connected: IP: 127.0.0.1 PORT: 8080 ``` - + ## Auto-Implementing Pickable for Enums No need to manually implement `Pickable` for enums: `Picker` auto-implements it for any type that implements `PickableEnum`, as long as it also implements `EnumTag` ✏️ @@ -335,28 +335,28 @@ pub enum Fruits { Banana, Orange, } - + // Implement PickableEnum for Fruits impl PickableEnum for Fruits {} ``` - + Now you can directly use `Picker` to parse this type ✏️ ```rust pack!(ResultFruit = Fruits); - + #[chain] fn handle_eat_fruit_entry(prev: EatFruitEntry) -> NextProcess { let fruit: Fruits = prev.pick("--fruit").unpack(); ResultFruit::new(fruit) } - + #[renderer] fn render_ate_fruit(prev: ResultFruit) { r_println!("Picked fruit: {:?}", *prev); } ``` - + That's all for `Picker`'s usage. In the next chapter, I'll introduce how to implement help docs for commands in **Mingling**.

-- cgit