cli_match

Macro cli_match 

Source
macro_rules! cli_match {
    ( $( $pattern:pat => $expr:expr ),* $(,)? ) => { ... };
}
Expand description

Command matching macro

This macro provides a convenient way to match command names and automatically parse the command line. It eliminates the need to manually call parse_command_line().

§Syntax

use cli_command::cli_match;
 
fn main() -> Result<(), Box<dyn std::error::Error>> {
    cli_match! {
        "command1" => { /* handle command1 */ Ok(()) },
        "command2" => { /* handle command2 */ Ok(()) },
        _ => { /* handle unknown commands */ Ok(()) }
    }
}

§Examples

use cli_command::{cli_match, cli_args};

fn start_server(port: u16, host: String) -> Result<(), Box<dyn std::error::Error>> {
    println!("Starting server on {}:{}", host, port);
    Ok(())
}

fn build_project(output: String, release: bool) -> Result<(), Box<dyn std::error::Error>> {
    println!("Building project to {} (release: {})", output, release);
    Ok(())
}

fn print_help() -> Result<(), Box<dyn std::error::Error>> {
    println!("Available commands: serve, build, help");
    Ok(())
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    cli_match! {
        "serve" => {
            let (port, host) = cli_args!(
                port: u16 = 8080,
                host: String = "localhost".to_string()
            );
            start_server(port, host)
        },
        "build" => {
            let (output, release) = cli_args!(
                output: String = "dist".to_string(),
                release: bool = false
            );
            build_project(output, release)
        },
        "help" => print_help(),
        _ => {
            eprintln!("Unknown command");
            print_help();
            Ok(())
        }
    }
}