macro_example/
macro_example.rs

1//! A comprehensive example demonstrating the cli_args! and cli_match! macros.
2//!
3//! This example shows how to use the convenient macros provided by cli-command
4//! to reduce boilerplate code while maintaining the same functionality.
5
6use cli_command::{cli_args, cli_match};
7
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    cli_match! {
10        "server" => {
11            println!("🚀 Starting server with macro-based argument parsing...");
12            start_server()
13        },
14        "client" => {
15            println!("📡 Starting client with macro-based argument parsing...");
16            start_client()
17        },
18        "config" => {
19            println!("⚙️  Managing configuration with macro-based argument parsing...");
20            manage_config()
21        },
22        "help" | "--help" | "-h" => {
23            print_help();
24            Ok(())
25        },
26        _ => {
27            eprintln!("❌ Unknown command");
28            print_help();
29            Ok(())
30        }
31    }
32}
33
34/// Start a server using the cli_args! macro for argument extraction
35fn start_server() -> Result<(), Box<dyn std::error::Error>> {
36    let (port, host, workers) = cli_args!(
37        port: u16 = 8080,
38        host: String = "localhost".to_string(),
39        workers: usize = 4
40    );
41
42    let cmd = cli_command::parse_command_line()?;
43    let ssl = cmd.contains_argument("ssl");
44    let verbose = cmd.contains_argument("verbose");
45    let config_file = cmd.get_argument("config-file");
46
47    println!("🌐 Server Configuration:");
48    println!("   Host: {}", host);
49    println!("   Port: {}", port);
50    println!("   Workers: {}", workers);
51    println!("   SSL: {}", ssl);
52    println!("   Verbose: {}", verbose);
53
54    if let Some(config) = config_file {
55        println!("   Config file: {}", config);
56    }
57
58    println!("✅ Server started successfully on {}:{}", host, port);
59
60    Ok(())
61}
62
63/// Start a client using the cli_args! macro for argument extraction
64fn start_client() -> Result<(), Box<dyn std::error::Error>> {
65    let (timeout, retries) = cli_args!(
66        timeout: u64 = 30,
67        retries: u32 = 3
68    );
69
70    let cmd = cli_command::parse_command_line()?;
71    let server_url =
72        cmd.get_argument_or_default("server-url", "http://localhost:8080".to_string())?;
73    let username = cmd.get_argument("username");
74    let password = cmd.get_argument("password");
75
76    println!("📡 Client Configuration:");
77    println!("   Server URL: {}", server_url);
78    println!("   Timeout: {}s", timeout);
79    println!("   Retries: {}", retries);
80
81    if let Some(user) = username {
82        println!("   Username: {}", user);
83    }
84
85    if let Some(pass) = password {
86        println!("   Password: {}", "*".repeat(pass.len()));
87    }
88
89    println!("✅ Client connected to server successfully");
90
91    Ok(())
92}
93
94/// Manage configuration using the cli_args! macro
95fn manage_config() -> Result<(), Box<dyn std::error::Error>> {
96    let (action, config_path, backup, force) = cli_args!(
97        action: String = "show".to_string(),
98        config_path: String = "./config.toml".to_string(),
99        backup: bool = true,
100        force: bool = false
101    );
102
103    println!("⚙️  Configuration Management:");
104    println!("   Action: {}", action);
105    println!("   Config path: {}", config_path);
106    println!("   Backup: {}", backup);
107    println!("   Force: {}", force);
108
109    match action.as_str() {
110        "show" => {
111            println!("📋 Current configuration:");
112            println!("   port = 8080");
113            println!("   host = \"localhost\"");
114            println!("   workers = 4");
115        }
116        "backup" => {
117            println!("💾 Creating backup of configuration...");
118            println!("✅ Backup created successfully");
119        }
120        "restore" => {
121            println!("🔄 Restoring configuration from backup...");
122            println!("✅ Configuration restored successfully");
123        }
124        _ => {
125            println!("❌ Unknown action: {}", action);
126            println!("Available actions: show, backup, restore");
127        }
128    }
129
130    Ok(())
131}
132
133fn print_help() {
134    println!("🔧 CLI Command Macro Example");
135    println!();
136    println!("This example demonstrates the cli_args! and cli_match! macros");
137    println!("from the cli-command crate for ergonomic argument parsing.");
138    println!();
139    println!("Usage:");
140    println!("  macro_example <COMMAND> [OPTIONS]");
141    println!();
142    println!("Commands:");
143    println!("  server    Start a server with configurable options");
144    println!("  client    Start a client with connection options");
145    println!("  config    Manage configuration files");
146    println!("  help      Show this help message");
147    println!();
148    println!("Server options:");
149    println!("  --port <PORT>            Server port (default: 8080)");
150    println!("  --host <HOST>            Server host (default: localhost)");
151    println!("  --workers <COUNT>        Number of worker threads (default: 4)");
152    println!("  --ssl                    Enable SSL/TLS (default: false)");
153    println!("  --verbose                Enable verbose logging (default: false)");
154    println!("  --config-file <FILE>     Configuration file path (optional)");
155    println!();
156    println!("Client options:");
157    println!("  --server-url <URL>       Server URL (default: http://localhost:8080)");
158    println!("  --timeout <SECONDS>      Connection timeout (default: 30)");
159    println!("  --retries <COUNT>        Number of retry attempts (default: 3)");
160    println!("  --username <USER>        Username for authentication (optional)");
161    println!("  --password <PASS>        Password for authentication (optional)");
162    println!();
163    println!("Config options:");
164    println!("  --action <ACTION>        Action to perform: show, backup, restore (default: show)");
165    println!("  --config-path <PATH>     Path to configuration file (default: ./config.toml)");
166    println!("  --backup                 Create backup before changes (default: true)");
167    println!("  --force                  Force operation without confirmation (default: false)");
168    println!();
169    println!("Examples:");
170    println!("  # Start server with custom port and SSL");
171    println!("  cargo run --example macro_example -- server --port 3000 --ssl --verbose");
172    println!();
173    println!("  # Start client with authentication");
174    println!("  cargo run --example macro_example -- client --server-url https://api.example.com --username admin --password secret");
175    println!();
176    println!("  # Show current configuration");
177    println!("  cargo run --example macro_example -- config --action show");
178    println!();
179    println!("  # Backup configuration");
180    println!("  cargo run --example macro_example -- config --action backup --config-path /etc/myapp.conf");
181    println!();
182    println!("🔍 Notice how cli_match! eliminates the need to manually parse command line");
183    println!("   and cli_args! eliminates boilerplate argument extraction code!");
184}