pub fn parse_command_line() -> Result<Command, CliError>
Expand description
Parses command line arguments from std::env::args()
.
This function automatically reads the command line arguments passed to the program
and parses them into a Command
struct. It skips the program name (first argument).
ยงReturns
Ok(Command)
- If parsing succeedsErr(CliError)
- If parsing fails
ยงExamples
use cli_command::parse_command_string;
// When called with: myapp serve --port 8080 --host localhost
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"));
Examples found in repository?
examples/simple_server.rs (line 10)
9fn main() -> Result<(), Box<dyn std::error::Error>> {
10 let cmd = parse_command_line()?;
11
12 match cmd.name.as_str() {
13 "serve" => {
14 println!("Starting HTTP server...");
15 start_server(&cmd)?;
16 }
17 "help" | "--help" | "-h" => {
18 print_help();
19 }
20 _ => {
21 println!("Unknown command: {}", cmd.name);
22 print_help();
23 }
24 }
25
26 Ok(())
27}
More examples
examples/file_processor.rs (line 9)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9 let cmd = parse_command_line()?;
10
11 match cmd.name.as_str() {
12 "compress" => {
13 println!("Compressing files...");
14 compress_files(&cmd)?;
15 }
16 "extract" => {
17 println!("Extracting files...");
18 extract_files(&cmd)?;
19 }
20 "list" => {
21 println!("Listing files...");
22 list_files(&cmd)?;
23 }
24 "help" | "--help" | "-h" => {
25 print_help();
26 }
27 _ => {
28 println!("Unknown command: {}", cmd.name);
29 print_help();
30 }
31 }
32
33 Ok(())
34}
examples/cli_match_example.rs (line 47)
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}
examples/macro_example.rs (line 42)
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}
examples/simple_macro_test.rs (line 19)
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}