pub struct Command {
pub name: String,
pub arguments: HashMap<String, Box<[String]>>,
}Expand description
Represents a parsed command with its name and arguments.
The Command struct holds the parsed command-line arguments in a structured format.
It provides convenient methods for accessing arguments with type conversion and error handling.
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("serve --port 8080 --host localhost").unwrap();
assert_eq!(cmd.name, "serve");
assert_eq!(cmd.get_argument("port"), Some("8080"));
assert_eq!(cmd.get_argument("host"), Some("localhost"));Fields§
§name: StringThe command name (first non-flag argument)
arguments: HashMap<String, Box<[String]>>Parsed arguments as a map of argument names to their values
Implementations§
Source§impl Command
impl Command
Sourcepub fn get_argument_nth_parameter_usize(
&self,
argument: &str,
nth: usize,
) -> Option<usize>
pub fn get_argument_nth_parameter_usize( &self, argument: &str, nth: usize, ) -> Option<usize>
Gets the nth parameter of an argument as a usize, if it exists and can be parsed.
§Arguments
argument- The name of the argumentnth- The zero-based index of the parameter
§Returns
Some(usize)- If the parameter exists and can be parsed as a usizeNone- If the argument doesn’t exist or the parameter can’t be parsed
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--numbers 1 2 3").unwrap();
assert_eq!(cmd.get_argument_nth_parameter_usize("numbers", 0), Some(1));
assert_eq!(cmd.get_argument_nth_parameter_usize("numbers", 1), Some(2));
assert_eq!(cmd.get_argument_nth_parameter_usize("numbers", 5), None);Sourcepub fn get_argument_nth_parameter(
&self,
argument: &str,
nth: usize,
) -> Option<&str>
pub fn get_argument_nth_parameter( &self, argument: &str, nth: usize, ) -> Option<&str>
Gets the nth parameter of an argument as a string slice, if it exists.
§Arguments
argument- The name of the argumentnth- The zero-based index of the parameter
§Returns
Some(&str)- If the parameter existsNone- If the argument doesn’t exist or the parameter is out of bounds
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--files a.txt b.txt c.txt").unwrap();
assert_eq!(cmd.get_argument_nth_parameter("files", 0), Some("a.txt"));
assert_eq!(cmd.get_argument_nth_parameter("files", 1), Some("b.txt"));
assert_eq!(cmd.get_argument_nth_parameter("files", 5), None);Sourcepub fn get_argument_nth_param_mandatory(
&self,
argument: &str,
nth: usize,
) -> Result<&str, CliError>
pub fn get_argument_nth_param_mandatory( &self, argument: &str, nth: usize, ) -> Result<&str, CliError>
Gets the nth parameter of an argument as a string slice, returning an error if missing.
§Arguments
argument- The name of the argumentnth- The zero-based index of the parameter
§Returns
Ok(&str)- If the parameter existsErr(CliError)- If the argument or parameter is missing
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--files a.txt b.txt").unwrap();
assert_eq!(cmd.get_argument_nth_param_mandatory("files", 0).unwrap(), "a.txt");
assert_eq!(cmd.get_argument_nth_param_mandatory("files", 1).unwrap(), "b.txt");Sourcepub fn get_argument_nth_param_mandatory_usize(
&self,
argument: &str,
nth: usize,
) -> Result<usize, CliError>
pub fn get_argument_nth_param_mandatory_usize( &self, argument: &str, nth: usize, ) -> Result<usize, CliError>
Gets the nth parameter of an argument as a usize, returning an error if missing or invalid.
§Arguments
argument- The name of the argumentnth- The zero-based index of the parameter
§Returns
Ok(usize)- If the parameter exists and can be parsedErr(CliError)- If the argument is missing or the parameter can’t be parsed
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--numbers 1 2 3").unwrap();
assert_eq!(cmd.get_argument_nth_param_mandatory_usize("numbers", 0).unwrap(), 1);
assert_eq!(cmd.get_argument_nth_param_mandatory_usize("numbers", 1).unwrap(), 2);Sourcepub fn contains_argument(&self, argument: &str) -> bool
pub fn contains_argument(&self, argument: &str) -> bool
Checks if an argument exists (regardless of whether it has values).
§Arguments
argument- The name of the argument to check
§Returns
true- If the argument existsfalse- If the argument doesn’t exist
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--verbose --port 8080").unwrap();
assert!(cmd.contains_argument("verbose"));
assert!(cmd.contains_argument("port"));
assert!(!cmd.contains_argument("debug"));Examples found in repository?
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}More examples
36fn compress_files(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
37 let input_files = cmd.get_argument_mandatory_all("input")?;
38 let output_file = cmd.get_argument_mandatory("output")?;
39
40 let compression_level: u8 = cmd.get_argument_or_default("level", 6)?;
41 let algorithm = cmd.get_argument_or_default("algorithm", "gzip".to_string())?;
42 let recursive = cmd.contains_argument("recursive") || cmd.contains_argument("r");
43 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
44
45 println!("Compression settings:");
46 println!(" Input files: {:?}", input_files);
47 println!(" Output file: {}", output_file);
48 println!(" Compression level: {}", compression_level);
49 println!(" Algorithm: {}", algorithm);
50 println!(" Recursive: {}", recursive);
51 println!(" Verbose: {}", verbose);
52
53 println!(
54 "\nCompressing {} files to {}...",
55 input_files.len(),
56 output_file
57 );
58
59 Ok(())
60}
61
62fn extract_files(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
63 let archive_file = cmd.get_argument_mandatory("archive")?;
64 let output_dir = cmd.get_argument_or_default("output-dir", ".".to_string())?;
65 let overwrite = cmd.contains_argument("overwrite");
66 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
67
68 println!("Extraction settings:");
69 println!(" Archive file: {}", archive_file);
70 println!(" Output directory: {}", output_dir);
71 println!(" Overwrite existing: {}", overwrite);
72 println!(" Verbose: {}", verbose);
73
74 println!("\nExtracting {} to {}...", archive_file, output_dir);
75
76 Ok(())
77}
78
79fn list_files(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
80 let archive_file = cmd.get_argument_mandatory("archive")?;
81 let detailed = cmd.contains_argument("detailed") || cmd.contains_argument("l");
82 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
83
84 println!("Listing files in: {}", archive_file);
85 println!("Detailed view: {}", detailed);
86 println!("Verbose: {}", verbose);
87
88 println!("\nArchive contents:");
89 println!(" file1.txt (1024 bytes)");
90 println!(" file2.txt (2048 bytes)");
91 println!(" subdir/file3.txt (512 bytes)");
92
93 Ok(())
94}29fn start_server(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
30 let host: IpAddr = cmd.get_argument_or_default("host", Ipv4Addr::new(127, 0, 0, 1).into())?;
31 let port: u16 = cmd.get_argument_or_default("port", 8080)?;
32 let workers: usize = cmd.get_argument_or_default("workers", 4)?;
33 let max_connections: usize = cmd.get_argument_or_default("max-connections", 1000)?;
34
35 let enable_ssl = cmd.contains_argument("ssl");
36 let enable_compression = cmd.contains_argument("compression");
37 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
38
39 let config_file = cmd.get_argument("config");
40
41 let addr = SocketAddr::new(host, port);
42
43 println!("Server configuration:");
44 println!(" Address: {}", addr);
45 println!(" Workers: {}", workers);
46 println!(" Max connections: {}", max_connections);
47 println!(" SSL enabled: {}", enable_ssl);
48 println!(" Compression enabled: {}", enable_compression);
49 println!(" Verbose logging: {}", verbose);
50
51 if let Some(config) = config_file {
52 println!(" Config file: {}", config);
53 }
54
55 println!("\nServer would start on {} with {} workers", addr, workers);
56
57 Ok(())
58}8fn main() -> Result<(), Box<dyn std::error::Error>> {
9 println!("🔧 Simple CLI Args Macro Demo");
10 println!();
11
12 let (name, age, email, port) = cli_args!(
13 name: String = "Anonymous".to_string(),
14 age: u32 = 25,
15 email: String = "user@example.com".to_string(),
16 port: u16 = 8080
17 );
18
19 let cmd = parse_command_line()?;
20 let is_active = cmd.contains_argument("is-active");
21
22 println!("📋 Parsed Arguments:");
23 println!(" Name: {}", name);
24 println!(" Age: {}", age);
25 println!(" Email: {}", email);
26 println!(" Active: {}", is_active);
27 println!(" Port: {}", port);
28
29 println!();
30 println!("✨ Notice how the cli_args! macro eliminated this boilerplate:");
31 println!(" let name = cmd.get_argument_or_default(\"name\", \"Anonymous\".to_string())?;");
32 println!(" let age = cmd.get_argument_or_default(\"age\", 25)?;");
33 println!(
34 " let email = cmd.get_argument_or_default(\"email\", \"user@example.com\".to_string())?;"
35 );
36 println!(" let is_active = cmd.get_argument_or_default(\"is_active\", true)?;");
37 println!(" let port = cmd.get_argument_or_default(\"port\", 8080)?;");
38
39 println!();
40 println!("🚀 Try running with different arguments:");
41 println!(" cargo run --example simple_macro_test -- --name Alice --age 30 --port 3000");
42 println!(" cargo run --example simple_macro_test -- --name Bob --email bob@company.com --is-active false");
43
44 Ok(())
45}Sourcepub fn get_argument(&self, argument: &str) -> Option<&str>
pub fn get_argument(&self, argument: &str) -> Option<&str>
Gets the first parameter of an argument as a string slice, if it exists.
§Arguments
argument- The name of the argument
§Returns
Some(&str)- If the argument exists and has at least one parameterNone- If the argument doesn’t exist or has no parameters
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--host localhost --port 8080").unwrap();
assert_eq!(cmd.get_argument("host"), Some("localhost"));
assert_eq!(cmd.get_argument("port"), Some("8080"));
assert_eq!(cmd.get_argument("debug"), None);Examples found in repository?
38fn start_server() -> Result<(), Box<dyn std::error::Error>> {
39 let (port, host, workers, ssl, verbose) = cli_args!(
40 port: u16 = 8080,
41 host: String = "localhost".to_string(),
42 workers: usize = 4,
43 ssl: bool = false,
44 verbose: bool = false
45 );
46
47 let cmd = cli_command::parse_command_line()?;
48 let config_file = cmd.get_argument("config-file");
49
50 println!("🌐 Server Configuration:");
51 println!(" Host: {}", host);
52 println!(" Port: {}", port);
53 println!(" Workers: {}", workers);
54 println!(" SSL: {}", ssl);
55 println!(" Verbose: {}", verbose);
56
57 if let Some(config) = config_file {
58 println!(" Config file: {}", config);
59 }
60
61 println!("✅ Server started successfully on {}:{}", host, port);
62
63 Ok(())
64}
65
66/// Start a client using both cli_match! and cli_args! macros
67fn start_client() -> Result<(), Box<dyn std::error::Error>> {
68 let (timeout, retries, server_url) = cli_args!(
69 timeout: u64 = 30,
70 retries: u32 = 3,
71 server_url: String = "http://localhost:8080".to_string()
72 );
73
74 let cmd = cli_command::parse_command_line()?;
75 let username = cmd.get_argument("username");
76 let password = cmd.get_argument("password");
77
78 println!("📡 Client Configuration:");
79 println!(" Server URL: {}", server_url);
80 println!(" Timeout: {}s", timeout);
81 println!(" Retries: {}", retries);
82
83 if let Some(user) = username {
84 println!(" Username: {}", user);
85 }
86
87 if let Some(pass) = password {
88 println!(" Password: {}", "*".repeat(pass.len()));
89 }
90
91 println!("✅ Client connected to server successfully");
92
93 Ok(())
94}More examples
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}29fn start_server(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
30 let host: IpAddr = cmd.get_argument_or_default("host", Ipv4Addr::new(127, 0, 0, 1).into())?;
31 let port: u16 = cmd.get_argument_or_default("port", 8080)?;
32 let workers: usize = cmd.get_argument_or_default("workers", 4)?;
33 let max_connections: usize = cmd.get_argument_or_default("max-connections", 1000)?;
34
35 let enable_ssl = cmd.contains_argument("ssl");
36 let enable_compression = cmd.contains_argument("compression");
37 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
38
39 let config_file = cmd.get_argument("config");
40
41 let addr = SocketAddr::new(host, port);
42
43 println!("Server configuration:");
44 println!(" Address: {}", addr);
45 println!(" Workers: {}", workers);
46 println!(" Max connections: {}", max_connections);
47 println!(" SSL enabled: {}", enable_ssl);
48 println!(" Compression enabled: {}", enable_compression);
49 println!(" Verbose logging: {}", verbose);
50
51 if let Some(config) = config_file {
52 println!(" Config file: {}", config);
53 }
54
55 println!("\nServer would start on {} with {} workers", addr, workers);
56
57 Ok(())
58}Sourcepub fn get_argument_mandatory(&self, argument: &str) -> Result<&str, CliError>
pub fn get_argument_mandatory(&self, argument: &str) -> Result<&str, CliError>
Gets the first parameter of an argument as a string slice, returning an error if missing.
§Arguments
argument- The name of the argument
§Returns
Ok(&str)- If the argument exists and has at least one parameterErr(CliError)- If the argument is missing
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--host localhost").unwrap();
assert_eq!(cmd.get_argument_mandatory("host").unwrap(), "localhost");Examples found in repository?
36fn compress_files(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
37 let input_files = cmd.get_argument_mandatory_all("input")?;
38 let output_file = cmd.get_argument_mandatory("output")?;
39
40 let compression_level: u8 = cmd.get_argument_or_default("level", 6)?;
41 let algorithm = cmd.get_argument_or_default("algorithm", "gzip".to_string())?;
42 let recursive = cmd.contains_argument("recursive") || cmd.contains_argument("r");
43 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
44
45 println!("Compression settings:");
46 println!(" Input files: {:?}", input_files);
47 println!(" Output file: {}", output_file);
48 println!(" Compression level: {}", compression_level);
49 println!(" Algorithm: {}", algorithm);
50 println!(" Recursive: {}", recursive);
51 println!(" Verbose: {}", verbose);
52
53 println!(
54 "\nCompressing {} files to {}...",
55 input_files.len(),
56 output_file
57 );
58
59 Ok(())
60}
61
62fn extract_files(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
63 let archive_file = cmd.get_argument_mandatory("archive")?;
64 let output_dir = cmd.get_argument_or_default("output-dir", ".".to_string())?;
65 let overwrite = cmd.contains_argument("overwrite");
66 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
67
68 println!("Extraction settings:");
69 println!(" Archive file: {}", archive_file);
70 println!(" Output directory: {}", output_dir);
71 println!(" Overwrite existing: {}", overwrite);
72 println!(" Verbose: {}", verbose);
73
74 println!("\nExtracting {} to {}...", archive_file, output_dir);
75
76 Ok(())
77}
78
79fn list_files(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
80 let archive_file = cmd.get_argument_mandatory("archive")?;
81 let detailed = cmd.contains_argument("detailed") || cmd.contains_argument("l");
82 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
83
84 println!("Listing files in: {}", archive_file);
85 println!("Detailed view: {}", detailed);
86 println!("Verbose: {}", verbose);
87
88 println!("\nArchive contents:");
89 println!(" file1.txt (1024 bytes)");
90 println!(" file2.txt (2048 bytes)");
91 println!(" subdir/file3.txt (512 bytes)");
92
93 Ok(())
94}Sourcepub fn get_argument_mandatory_usize(
&self,
argument: &str,
) -> Result<usize, CliError>
pub fn get_argument_mandatory_usize( &self, argument: &str, ) -> Result<usize, CliError>
Gets the first parameter of an argument as a usize, returning an error if missing or invalid.
§Arguments
argument- The name of the argument
§Returns
Ok(usize)- If the argument exists and can be parsed as a usizeErr(CliError)- If the argument is missing or can’t be parsed
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--port 8080").unwrap();
assert_eq!(cmd.get_argument_mandatory_usize("port").unwrap(), 8080);Sourcepub fn get_argument_usize(&self, argument: &str) -> Option<usize>
pub fn get_argument_usize(&self, argument: &str) -> Option<usize>
Gets the first parameter of an argument as a usize, if it exists and can be parsed.
§Arguments
argument- The name of the argument
§Returns
Some(usize)- If the argument exists and can be parsed as a usizeNone- If the argument doesn’t exist or can’t be parsed
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--port 8080 --workers 4").unwrap();
assert_eq!(cmd.get_argument_usize("port"), Some(8080));
assert_eq!(cmd.get_argument_usize("workers"), Some(4));
assert_eq!(cmd.get_argument_usize("debug"), None);Sourcepub fn get_argument_i32(&self, argument: &str) -> Option<i32>
pub fn get_argument_i32(&self, argument: &str) -> Option<i32>
Gets the first parameter of an argument as an i32, if it exists and can be parsed.
§Arguments
argument- The name of the argument
§Returns
Some(i32)- If the argument exists and can be parsed as an i32None- If the argument doesn’t exist or can’t be parsed
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--port 8080 --timeout 30").unwrap();
assert_eq!(cmd.get_argument_i32("port"), Some(8080));
assert_eq!(cmd.get_argument_i32("timeout"), Some(30));
assert_eq!(cmd.get_argument_i32("debug"), None);Sourcepub fn get_argument_f64(&self, argument: &str) -> Option<f64>
pub fn get_argument_f64(&self, argument: &str) -> Option<f64>
Gets the first parameter of an argument as a f64, if it exists and can be parsed.
§Arguments
argument- The name of the argument
§Returns
Some(f64)- If the argument exists and can be parsed as an f64None- If the argument doesn’t exist or can’t be parsed
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--ratio 0.5 --threshold 1.23").unwrap();
assert_eq!(cmd.get_argument_f64("ratio"), Some(0.5));
assert_eq!(cmd.get_argument_f64("threshold"), Some(1.23));
assert_eq!(cmd.get_argument_f64("debug"), None);Sourcepub fn get_argument_bool(&self, argument: &str) -> Option<bool>
pub fn get_argument_bool(&self, argument: &str) -> Option<bool>
Gets the first parameter of an argument as a bool, if it exists and can be parsed.
§Arguments
argument- The name of the argument
§Returns
Some(bool)- If the argument exists and can be parsed as a boolNone- If the argument doesn’t exist or can’t be parsed
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--enabled true --disabled false").unwrap();
assert_eq!(cmd.get_argument_bool("enabled"), Some(true));
assert_eq!(cmd.get_argument_bool("disabled"), Some(false));
assert_eq!(cmd.get_argument_bool("debug"), None);Sourcepub fn get_argument_all(&self, argument: &str) -> Option<&Box<[String]>>
pub fn get_argument_all(&self, argument: &str) -> Option<&Box<[String]>>
Gets all parameters of an argument as a slice of strings, if it exists.
§Arguments
argument- The name of the argument
§Returns
Some(&Box<[String]>)- If the argument existsNone- If the argument doesn’t exist
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--files a.txt b.txt c.txt").unwrap();
let files = cmd.get_argument_all("files").unwrap();
assert_eq!(files.len(), 3);
assert_eq!(&files[0], "a.txt");
assert_eq!(&files[1], "b.txt");
assert_eq!(&files[2], "c.txt");Sourcepub fn get_argument_mandatory_all(
&self,
argument: &str,
) -> Result<&Box<[String]>, CliError>
pub fn get_argument_mandatory_all( &self, argument: &str, ) -> Result<&Box<[String]>, CliError>
Gets all parameters of an argument as a slice of strings, returning an error if missing.
§Arguments
argument- The name of the argument
§Returns
Ok(&Box<[String]>)- If the argument existsErr(CliError)- If the argument is missing
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--files a.txt b.txt").unwrap();
let files = cmd.get_argument_mandatory_all("files").unwrap();
assert_eq!(files.len(), 2);Examples found in repository?
36fn compress_files(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
37 let input_files = cmd.get_argument_mandatory_all("input")?;
38 let output_file = cmd.get_argument_mandatory("output")?;
39
40 let compression_level: u8 = cmd.get_argument_or_default("level", 6)?;
41 let algorithm = cmd.get_argument_or_default("algorithm", "gzip".to_string())?;
42 let recursive = cmd.contains_argument("recursive") || cmd.contains_argument("r");
43 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
44
45 println!("Compression settings:");
46 println!(" Input files: {:?}", input_files);
47 println!(" Output file: {}", output_file);
48 println!(" Compression level: {}", compression_level);
49 println!(" Algorithm: {}", algorithm);
50 println!(" Recursive: {}", recursive);
51 println!(" Verbose: {}", verbose);
52
53 println!(
54 "\nCompressing {} files to {}...",
55 input_files.len(),
56 output_file
57 );
58
59 Ok(())
60}Sourcepub fn get_argument_or_default<T>(
&self,
argument: &str,
default: T,
) -> Result<T, CliError>
pub fn get_argument_or_default<T>( &self, argument: &str, default: T, ) -> Result<T, CliError>
Gets the first parameter of an argument with type conversion, or returns a default value if missing.
This method attempts to parse the argument value as the specified type T. If the argument
is missing, it returns the provided default value instead of an error.
§Arguments
argument- The name of the argumentdefault- The default value to return if the argument is missing
§Returns
Ok(T)- If the argument exists and can be parsed, or if missing (returns default)Err(CliError)- If the argument exists but can’t be parsed as the target type
§Examples
use cli_command::{Command, parse_command_string};
let cmd = parse_command_string("--port 8080").unwrap();
let port: u16 = cmd.get_argument_or_default("port", 3000).unwrap();
assert_eq!(port, 8080);
let timeout: u64 = cmd.get_argument_or_default("timeout", 30).unwrap();
assert_eq!(timeout, 30); // Uses default since timeout not providedExamples found in repository?
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}More examples
36fn compress_files(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
37 let input_files = cmd.get_argument_mandatory_all("input")?;
38 let output_file = cmd.get_argument_mandatory("output")?;
39
40 let compression_level: u8 = cmd.get_argument_or_default("level", 6)?;
41 let algorithm = cmd.get_argument_or_default("algorithm", "gzip".to_string())?;
42 let recursive = cmd.contains_argument("recursive") || cmd.contains_argument("r");
43 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
44
45 println!("Compression settings:");
46 println!(" Input files: {:?}", input_files);
47 println!(" Output file: {}", output_file);
48 println!(" Compression level: {}", compression_level);
49 println!(" Algorithm: {}", algorithm);
50 println!(" Recursive: {}", recursive);
51 println!(" Verbose: {}", verbose);
52
53 println!(
54 "\nCompressing {} files to {}...",
55 input_files.len(),
56 output_file
57 );
58
59 Ok(())
60}
61
62fn extract_files(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
63 let archive_file = cmd.get_argument_mandatory("archive")?;
64 let output_dir = cmd.get_argument_or_default("output-dir", ".".to_string())?;
65 let overwrite = cmd.contains_argument("overwrite");
66 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
67
68 println!("Extraction settings:");
69 println!(" Archive file: {}", archive_file);
70 println!(" Output directory: {}", output_dir);
71 println!(" Overwrite existing: {}", overwrite);
72 println!(" Verbose: {}", verbose);
73
74 println!("\nExtracting {} to {}...", archive_file, output_dir);
75
76 Ok(())
77}29fn start_server(cmd: &Command) -> Result<(), Box<dyn std::error::Error>> {
30 let host: IpAddr = cmd.get_argument_or_default("host", Ipv4Addr::new(127, 0, 0, 1).into())?;
31 let port: u16 = cmd.get_argument_or_default("port", 8080)?;
32 let workers: usize = cmd.get_argument_or_default("workers", 4)?;
33 let max_connections: usize = cmd.get_argument_or_default("max-connections", 1000)?;
34
35 let enable_ssl = cmd.contains_argument("ssl");
36 let enable_compression = cmd.contains_argument("compression");
37 let verbose = cmd.contains_argument("verbose") || cmd.contains_argument("v");
38
39 let config_file = cmd.get_argument("config");
40
41 let addr = SocketAddr::new(host, port);
42
43 println!("Server configuration:");
44 println!(" Address: {}", addr);
45 println!(" Workers: {}", workers);
46 println!(" Max connections: {}", max_connections);
47 println!(" SSL enabled: {}", enable_ssl);
48 println!(" Compression enabled: {}", enable_compression);
49 println!(" Verbose logging: {}", verbose);
50
51 if let Some(config) = config_file {
52 println!(" Config file: {}", config);
53 }
54
55 println!("\nServer would start on {} with {} workers", addr, workers);
56
57 Ok(())
58}