### Initialize gumdrop options Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Basic setup for using the gumdrop crate. ```rust use gumdrop::{Options, ParsingStyle); ``` -------------------------------- ### Get General Usage String Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Returns a static string detailing usage and help for all supported options. This string should not end with a newline. ```rust fn usage() -> &'static str where Self: Sized; ``` -------------------------------- ### Get Command List Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Returns a string listing available commands and their help text, separated by newlines. The string should not end with a newline. For enums, this is the same as `usage`. ```rust fn command_list() -> Option<&'static str> where Self: Sized; ``` -------------------------------- ### Get Self Usage String Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Returns a static string detailing usage and help for the current options instance, including subcommands if selected. This string should not end with a newline. ```rust fn self_usage(&self) -> &'static str; ``` -------------------------------- ### ParsingStyle Usage Example Source: https://docs.rs/gumdrop/latest/gumdrop/enum.ParsingStyle.html Demonstrates how to use the ParsingStyle enum with the `parse_args` function to control argument parsing behavior. ```APIDOC ## Examples ```rust use gumdrop::{Options, ParsingStyle}; #[derive(Options)] struct MyOptions { // If the "-o" is parsed as an option, this will be `true`. option: bool, // All free (non-option) arguments will be collected into this Vec. #[options(free)] free: Vec, } // Command line arguments. let args = &["foo", "-o", "bar"]; // Using the `AllOptions` parsing style, the "-o" argument in the middle of args // will be parsed as an option. let opts = MyOptions::parse_args(args, ParsingStyle::AllOptions).unwrap(); assert_eq!(opts.option, true); assert_eq!(opts.free, vec!["foo", "bar"]); // Using the `StopAtFirstFree` option, the first non-option argument will terminate // option parsing. That means "-o" is treated as a free argument. let opts = MyOptions::parse_args(args, ParsingStyle::StopAtFirstFree).unwrap(); assert_eq!(opts.option, false); assert_eq!(opts.free, vec!["foo", "-o", "bar"]); ``` ``` -------------------------------- ### Get Self Command List Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Returns a listing of available commands and help text for the current options instance, including subcommands if selected. Commands are separated by newlines and the string should not end with a newline. ```rust fn self_command_list(&self) -> Option<&'static str>; ``` -------------------------------- ### Get Specific Command Usage Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Returns a usage string for a named command, or `None` if the command does not exist. Command descriptions are separated by newlines and the string should not end with a newline. ```rust fn command_usage(command: &str) -> Option<&'static str> where Self: Sized; ``` -------------------------------- ### Configure ParsingStyle for Argument Processing Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Demonstrates how to use AllOptions and StopAtFirstFree styles to change how non-option arguments are handled during parsing. ```rust /// #[derive(Options)] /// struct MyOptions { /// // If the "-o" is parsed as an option, this will be `true`. /// option: bool, /// // All free (non-option) arguments will be collected into this Vec. /// #[options(free)] /// free: Vec, /// } /// /// // Command line arguments. /// let args = &["foo", "-o", "bar"]; /// /// // Using the `AllOptions` parsing style, the "-o" argument in the middle of args /// // will be parsed as an option. /// let opts = MyOptions::parse_args(args, ParsingStyle::AllOptions).unwrap(); /// /// assert_eq!(opts.option, true); /// assert_eq!(opts.free, vec!["foo", "bar"]); /// /// // Using the `StopAtFirstFree` option, the first non-option argument will terminate /// // option parsing. That means "-o" is treated as a free argument. /// let opts = MyOptions::parse_args(args, ParsingStyle::StopAtFirstFree).unwrap(); /// /// assert_eq!(opts.option, false); /// assert_eq!(opts.free, vec!["foo", "-o", "bar"]); ``` -------------------------------- ### Implement CloneToUninit (Nightly) Source: https://docs.rs/gumdrop/latest/gumdrop/enum.Opt.html A nightly-only experimental API for copying Opt variants to uninitialized memory. Use with caution. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Compare ParsingStyle Behaviors Source: https://docs.rs/gumdrop/latest/gumdrop/enum.ParsingStyle.html Demonstrates the difference between AllOptions and StopAtFirstFree parsing styles when processing command-line arguments. ```rust use gumdrop::{Options, ParsingStyle}; #[derive(Options)] struct MyOptions { // If the "-o" is parsed as an option, this will be `true`. option: bool, // All free (non-option) arguments will be collected into this Vec. #[options(free)] free: Vec, } // Command line arguments. let args = &["foo", "-o", "bar"]; // Using the `AllOptions` parsing style, the "-o" argument in the middle of args // will be parsed as an option. let opts = MyOptions::parse_args(args, ParsingStyle::AllOptions).unwrap(); assert_eq!(opts.option, true); assert_eq!(opts.free, vec!["foo", "bar"]); // Using the `StopAtFirstFree` option, the first non-option argument will terminate // option parsing. That means "-o" is treated as a free argument. let opts = MyOptions::parse_args(args, ParsingStyle::StopAtFirstFree).unwrap(); assert_eq!(opts.option, false); assert_eq!(opts.free, vec!["foo", "-o", "bar"]); ``` -------------------------------- ### Get Command Name Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Returns the name of the parsed command, if present. This is implemented by `derive(Options)` based on struct fields or enum variants. ```rust fn command_name(&self) -> Option<&'static str> ``` -------------------------------- ### Argument Parsing with MyOptions Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Demonstrates parsing command-line arguments into a struct with different parsing styles. ```APIDOC ## Parsing Arguments with MyOptions ### Description This section shows how to parse command-line arguments into a custom struct `MyOptions` using different parsing strategies. ### Method `MyOptions::parse_args(args, parsing_style)` ### Endpoint N/A (This is a library function, not an API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example arguments let args = &["foo", "-o", "bar"]; // Using AllOptions parsing style let opts_all = MyOptions::parse_args(args, ParsingStyle::AllOptions).unwrap(); // opts_all.option will be true, opts_all.free will be vec!["foo", "bar"] // Using StopAtFirstFree parsing style let opts_stop = MyOptions::parse_args(args, ParsingStyle::StopAtFirstFree).unwrap(); // opts_stop.option will be false, opts_stop.free will be vec!["foo", "-o", "bar"] ``` ### Response #### Success Response (200) N/A (This is a library function, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### Get Subcommand Instance Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Returns the subcommand instance if present. Ensure this method never returns `self` to avoid infinite loops or stack overflows. ```rust fn command(&self) -> Option<&dyn Options> ``` -------------------------------- ### Basic Options Parsing Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Demonstrates how to define and parse basic options using Gumdrop's derive macro. ```APIDOC ## Basic Options Parsing Example ### Description This example shows a simple struct `InstallOpts` with an optional `dir` field, which can be provided via command-line arguments. ### Method N/A (This is a code example demonstrating struct definition and parsing) ### Endpoint N/A ### Request Body N/A ### Request Example ```rust use gumdrop::Options; #[derive(Debug, Options)] struct InstallOpts { #[options(help = "target directory")] dir: Option, } fn main() { // Assuming arguments are passed via command line // Example: program --dir /path/to/install let opts = InstallOpts::parse_args_default_or_exit(); println!("{:#?}", opts); } ``` ### Response N/A (This is a code example demonstrating struct definition and parsing) ### Response Example N/A ``` -------------------------------- ### Parser::new Source: https://docs.rs/gumdrop/latest/gumdrop/struct.Parser.html Initializes a new parser instance for a given slice of arguments. ```APIDOC ## pub fn new(args: &'a [S], style: ParsingStyle) -> Parser<'a, S> ### Description Returns a new parser for the given series of arguments. The provided slice should not contain the program name as its first element. ### Parameters #### Request Body - **args** (&'a [S]) - Required - A slice of string-like values to be parsed. - **style** (ParsingStyle) - Required - The parsing style to apply. ``` -------------------------------- ### Initialize and Iterate Parser Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Methods to create a new parser instance and retrieve the next option or argument from the input slice. ```rust impl<'a, S: 'a + AsRef> Parser<'a, S> { /// Returns a new parser for the given series of arguments. /// /// The given slice should **not** contain the program name as its first /// element. pub fn new(args: &'a [S], style: ParsingStyle) -> Parser<'a, S> { Parser{ args: args.iter(), cur: None, style: style, terminated: false, } } /// Returns the next option or `None` if no options remain. pub fn next_opt(&mut self) -> Option> { if let Some(mut cur) = self.cur.take() { if let Some(opt) = cur.next() { self.cur = Some(cur); return Some(Opt::Short(opt)); } } if self.terminated { return self.args.next().map(|s| Opt::Free(s.as_ref())); } match self.args.next().map(|s| s.as_ref()) { Some(arg @ "-") => { if self.style == ParsingStyle::StopAtFirstFree { self.terminated = true; } Some(Opt::Free(arg)) } Some("--") => { self.terminated = true; self.args.next().map(|s| Opt::Free(s.as_ref())) } Some(long) if long.starts_with("--") => { match long.find('=') { Some(pos) => Some(Opt::LongWithArg( &long[2..pos], &long[pos + 1..])), None => Some(Opt::Long(&long[2..])) } } Some(short) if short.starts_with('-') => { let mut chars = short[1..].chars(); let res = chars.next().map(Opt::Short); self.cur = Some(chars); res } Some(free) => { if self.style == ParsingStyle::StopAtFirstFree { self.terminated = true; } Some(Opt::Free(free)) } None => None } } /// Returns the next argument to an option or `None` if none remain. pub fn next_arg(&mut self) -> Option<&'a str> { if let Some(cur) = self.cur.take() { let arg = cur.as_str(); if !arg.is_empty() { return Some(arg); } } self.args.next().map(|s| s.as_ref()) } } ``` -------------------------------- ### Usage Information Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Provides methods to retrieve usage and help strings for options and commands. ```APIDOC ## Usage Methods ### fn usage() -> &'static str #### Description Returns a string showing usage and help for each supported option. Option descriptions are separated by newlines. The returned string should not end with a newline. ### fn self_usage(&self) -> &'static str #### Description Returns a string showing usage and help for this options instance. In contrast to `usage`, this method will return usage for a subcommand, if one is selected. Option descriptions are separated by newlines. The returned string should not end with a newline. ### fn command_usage(command: &str) -> Option<&'static str> #### Description Returns a usage string for the named command. If the named command does not exist, `None` is returned. Command descriptions are separated by newlines. The returned string should not end with a newline. ### fn command_list() -> Option<&'static str> #### Description Returns a string listing available commands and help text. Commands are separated by newlines. The string should not end with a newline. For `enum` types with `derive(Options)`, this is the same as `usage`. For `struct` types containing a field marked `#[options(command)]`, `usage` is called on the command type. ### fn self_command_list(&self) -> Option<&'static str> #### Description Returns a listing of available commands and help text. In contrast to `usage`, this method will return command list for a subcommand, if one is selected. Commands are separated by newlines. The string should not end with a newline. ### Method `Self::usage`, `self.self_usage()`, `Self::command_usage`, `Self::command_list`, `self.self_command_list()` ### Response - Returns `&'static str` containing usage information or `None` if the command is not found. ``` -------------------------------- ### Test Parsing Styles Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Compares argument parsing behavior between `AllOptions` and `StopAtFirstFree` styles using the same input arguments. ```rust #[test] fn test_parsing_style() { let args = &["-a", "b", "-c", "--d"]; let mut p = Parser::new(args, ParsingStyle::AllOptions); assert_matches!(p.next_opt(), Some(Opt::Short('a'))); assert_matches!(p.next_opt(), Some(Opt::Free("b"))); assert_matches!(p.next_opt(), Some(Opt::Short('c'))); assert_matches!(p.next_opt(), Some(Opt::Long("d"))); assert_matches!(p.next_opt(), None); let mut p = Parser::new(args, ParsingStyle::StopAtFirstFree); assert_matches!(p.next_opt(), Some(Opt::Short('a'))); assert_matches!(p.next_opt(), Some(Opt::Free("b"))); assert_matches!(p.next_opt(), Some(Opt::Free("-c"))); assert_matches!(p.next_opt(), Some(Opt::Free("--d"))); assert_matches!(p.next_opt(), None); } ``` -------------------------------- ### Define Basic Command-Line Options Source: https://docs.rs/gumdrop/latest/gumdrop/index.html Use the Options derive macro to define a struct for command-line arguments. Fields can be configured with attributes for help text, meta variables, and parsing behavior. ```rust use gumdrop::Options; // Defines options that can be parsed from the command line. // // `derive(Options)` will generate an implementation of the trait `Options`. // Each field must either have a `Default` implementation or an inline // default value provided. // // (`Debug` is derived here only for demonstration purposes.) #[derive(Debug, Options)] struct MyOptions { // Contains "free" arguments -- those that are not options. // If no `free` field is declared, free arguments will result in an error. #[options(free)] free: Vec, // Boolean options are treated as flags, taking no additional values. // The optional `help` attribute is displayed in `usage` text. // // A boolean field named `help` is automatically given the `help_flag` attribute. // The `parse_args_or_exit` and `parse_args_default_or_exit` functions use help flags // to automatically display usage to the user. #[options(help = "print help message")] help: bool, // Non-boolean fields will take a value from the command line. // Wrapping the type in an `Option` is not necessary, but provides clarity. #[options(help = "give a string argument")] string: Option, // A field can be any type that implements `FromStr`. // The optional `meta` attribute is displayed in `usage` text. #[options(help = "give a number as an argument", meta = "N")] number: Option, // A `Vec` field will accumulate all values received from the command line. #[options(help = "give a list of string items")] item: Vec, // The `count` flag will treat the option as a counter. // Each time the option is encountered, the field is incremented. #[options(count, help = "increase a counting value")] count: u32, // Option names are automatically generated from field names, but these // can be overriden. The attributes `short = "?"`, `long = "..."`, // `no_short`, and `no_long` are used to control option names. #[options(no_short, help = "this option has no short form")] long_option_only: bool, } fn main() { let opts = MyOptions::parse_args_default_or_exit(); println!("{:#?}", opts); } ``` -------------------------------- ### Test Parser with AllOptions Style Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Tests the `Parser`'s ability to handle various argument formats including short options, free arguments, options with arguments, and the `--` separator. ```rust #[test] fn test_parser() { let args = &["-a", "b", "-cde", "arg", "-xfoo", "--long", "--opt=val", "--", "y", "-z"]; let mut p = Parser::new(args, ParsingStyle::AllOptions); assert_matches!(p.next_opt(), Some(Opt::Short('a'))); assert_matches!(p.next_opt(), Some(Opt::Free("b"))); assert_matches!(p.next_opt(), Some(Opt::Short('c'))); assert_matches!(p.next_opt(), Some(Opt::Short('d'))); assert_matches!(p.next_opt(), Some(Opt::Short('e'))); assert_matches!(p.next_arg(), Some("arg")); assert_matches!(p.next_opt(), Some(Opt::Short('x'))); assert_matches!(p.next_arg(), Some("foo")); assert_matches!(p.next_opt(), Some(Opt::Long("long"))); assert_matches!(p.next_opt(), Some(Opt::LongWithArg("opt", "val"))); assert_matches!(p.next_opt(), Some(Opt::Free("y"))); assert_matches!(p.next_opt(), Some(Opt::Free("-z"))); assert_matches!(p.next_opt(), None); } ``` -------------------------------- ### Check if Help is Requested Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Returns `true` if the user requested help information via a help option, `false` otherwise. The default implementation returns `false`. ```rust fn help_requested(&self) -> bool ``` -------------------------------- ### Parse Arguments from Environment (Default Style, with Exit) Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Parses arguments from the environment using the default `ParsingStyle`. Errors cause process exit, and help options display usage before exiting. ```rust /// Parses arguments from the environment, using the default /// [parsing style](enum.ParsingStyle.html). /// /// If an error is encountered, the error is printed to `stderr` and the /// process will exit with status code `2`. /// /// If the user supplies a help option, option usage will be printed to /// `stderr` and the process will exit with status code `0`. /// /// Otherwise, the parsed options are returned. /// /// # Panics /// /// If any argument to the process is not valid unicode. pub fn parse_args_default_or_exit() -> T { T::parse_args_default_or_exit() } ``` -------------------------------- ### Opt Enum Blanket Implementations Source: https://docs.rs/gumdrop/latest/gumdrop/enum.Opt.html Shows blanket implementations for the Opt enum, including Any, Borrow, BorrowMut, CloneToUninit, From, Into, ToOwned, TryFrom, and TryInto. ```APIDOC ### Blanket Implementations #### impl Any for T ##### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. #### impl Borrow for T ##### fn borrow(&self) -> &T Immutably borrows from an owned value. #### impl BorrowMut for T ##### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. #### impl CloneToUninit for T ##### unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. #### impl From for T ##### fn from(t: T) -> T Returns the argument unchanged. #### impl Into for T ##### fn into(self) -> U Calls `U::from(self)`. #### impl ToOwned for T ##### type Owned = T ##### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. ##### fn clone_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. #### impl TryFrom for T ##### type Error = Infallible ##### fn try_from(value: U) -> Result>::Error> Performs the conversion. #### impl TryInto for T ##### type Error = >::Error ##### fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Implement PartialEq for Opt Source: https://docs.rs/gumdrop/latest/gumdrop/enum.Opt.html Enables comparison of Opt variants for equality. Use this to check if two options are the same. ```rust fn eq(&self, other: &Opt<'a>) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Core Traits and Macros Source: https://docs.rs/gumdrop/latest/index.html Core components for defining and implementing option parsing logic. ```APIDOC ## Traits ### Options Implements a set of options parsed from command line arguments. ## Derive Macros ### Options Derives the `gumdrop::Options` trait for `struct` and `enum` items. ``` -------------------------------- ### Core Components Source: https://docs.rs/gumdrop/latest/gumdrop/index.html Key structures and traits used for defining and parsing options. ```APIDOC ## Structs - **Error**: Represents an error encountered during argument parsing. - **Parser**: Parses options from a series of &str-like values. ## Enums - **Opt**: Represents an option parsed from a Parser. - **ParsingStyle**: Controls behavior of free arguments in Parser. ## Traits - **Options**: Implements a set of options parsed from command line arguments. ## Derive Macros - **Options**: Derives the gumdrop::Options trait for struct and enum items. ``` -------------------------------- ### Define and Parse Basic Options with Gumdrop Source: https://docs.rs/gumdrop Use `#[derive(Options)]` on a struct to define command-line options. Fields with `Default` or inline defaults are required. Boolean fields act as flags, while others accept values. Free arguments are collected in a `Vec` field. ```rust use gumdrop::Options; // Defines options that can be parsed from the command line. // // `derive(Options)` will generate an implementation of the trait `Options`. // Each field must either have a `Default` implementation or an inline // default value provided. // // (`Debug` is derived here only for demonstration purposes.) #[derive(Debug, Options)] struct MyOptions { // Contains "free" arguments -- those that are not options. // If no `free` field is declared, free arguments will result in an error. #[options(free)] free: Vec, // Boolean options are treated as flags, taking no additional values. // The optional `help` attribute is displayed in `usage` text. // // A boolean field named `help` is automatically given the `help_flag` attribute. // The `parse_args_or_exit` and `parse_args_default_or_exit` functions use help flags // to automatically display usage to the user. #[options(help = "print help message")] help: bool, // Non-boolean fields will take a value from the command line. // Wrapping the type in an `Option` is not necessary, but provides clarity. #[options(help = "give a string argument")] string: Option, // A field can be any type that implements `FromStr`. // The optional `meta` attribute is displayed in `usage` text. #[options(help = "give a number as an argument", meta = "N")] number: Option, // A `Vec` field will accumulate all values received from the command line. #[options(help = "give a list of string items")] item: Vec, // The `count` flag will treat the option as a counter. // Each time the option is encountered, the field is incremented. #[options(count, help = "increase a counting value")] count: u32, // Option names are automatically generated from field names, but these // can be overriden. The attributes `short = "?"`, `long = "..."`, // `no_short`, and `no_long` are used to control option names. #[options(no_short, help = "this option has no short form")] long_option_only: bool, } fn main() { let opts = MyOptions::parse_args_default_or_exit(); println!("{:#?}", opts); } ``` -------------------------------- ### Parse Arguments with Default Settings Source: https://docs.rs/gumdrop/latest/gumdrop/fn.parse_args_default_or_exit.html Parses arguments from the environment using the default parsing style. Exits with status code 2 on error or 0 if help is requested. ```rust pub fn parse_args_default_or_exit() -> T ``` -------------------------------- ### Define Basic Options with Derive Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Use the Options derive macro to define a struct for command-line arguments. ```rust //! #[derive(Debug, Options)] //! struct InstallOpts { //! #[options(help = "target directory")] //! dir: Option, //! } //! //! fn main() { //! let opts = MyOptions::parse_args_default_or_exit(); //! //! println!("{:#?}", opts); //! } ``` -------------------------------- ### Implement Copy and Eq for Opt Source: https://docs.rs/gumdrop/latest/gumdrop/enum.Opt.html Indicates that Opt variants are trivially copyable and support full equality comparison. This allows for direct assignment and comparison without ownership concerns. ```rust impl<'a> Copy for Opt<'a> ``` ```rust impl<'a> Eq for Opt<'a> ``` -------------------------------- ### Core Traits and Macros Source: https://docs.rs/gumdrop Core components for defining and implementing argument parsing logic. ```APIDOC ## Options (Trait) ### Description Implements a set of options parsed from command line arguments. ## Options (Derive Macro) ### Description Derives the `gumdrop::Options` trait for `struct` and `enum` items. ``` -------------------------------- ### Implement Debug for Opt Source: https://docs.rs/gumdrop/latest/gumdrop/enum.Opt.html Allows Opt variants to be formatted for debugging output. This is useful for inspecting the state of options during development. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Define command parsing and usage methods Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Trait methods for parsing specific commands and retrieving usage or command list strings. ```rust fn parse_command>(name: &str, parser: &mut Parser) -> Result where Self: Sized; fn usage() -> &'static str where Self: Sized; fn self_usage(&self) -> &'static str; fn command_usage(command: &str) -> Option<&'static str> where Self: Sized; fn command_list() -> Option<&'static str> where Self: Sized; fn self_command_list(&self) -> Option<&'static str>; ``` -------------------------------- ### Implement StructuralPartialEq for Opt Source: https://docs.rs/gumdrop/latest/gumdrop/enum.Opt.html Provides structural equality comparison for Opt variants. This is often used in generic contexts. ```rust impl<'a> StructuralPartialEq for Opt<'a> ``` -------------------------------- ### Parser::next_opt Source: https://docs.rs/gumdrop/latest/gumdrop/struct.Parser.html Retrieves the next option from the parser. ```APIDOC ## pub fn next_opt(&mut self) -> Option> ### Description Returns the next option identified by the parser, or None if no options remain. ### Response #### Success Response (200) - **Option>** - The next parsed option or None. ``` -------------------------------- ### Implement Clone for Opt Source: https://docs.rs/gumdrop/latest/gumdrop/enum.Opt.html Provides the ability to create a copy of an Opt variant. This is a standard implementation for types that can be duplicated. ```rust fn clone(&self) -> Opt<'a> ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Custom Parsing Functions Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Illustrates how to use custom parsing functions for option fields, including functions that may fail. ```APIDOC ## Custom Parsing Functions Example ### Description This example defines a `MyOptions` struct with fields that require custom parsing logic: `hex` is parsed from hexadecimal, and `upper` is converted to uppercase. ### Method N/A (This is a code example demonstrating struct definition and parsing) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```rust use gumdrop::Options; use std::str::FromStr; #[derive(Debug, Options)] struct MyOptions { // `try_from_str = "..."` supplies a conversion function that may fail #[options(help = "a hexadecimal value", parse(try_from_str = "parse_hex"))] hex: u32, // `from_str = "..."` supplies a conversion function that always succeeds #[options(help = "a string that becomes uppercase", parse(from_str = "to_upper"))] upper: String, } fn parse_hex(s: &str) -> Result { u32::from_str_radix(s, 16) } fn to_upper(s: &str) -> String { s.to_uppercase() } fn main() { // Assuming arguments are passed via command line // Example: program --hex 1a2b --upper hello let opts = MyOptions::parse_args_default_or_exit(); println!("{:#?}", opts); } ``` ### Response N/A (This is a code example demonstrating struct definition and parsing) ### Response Example N/A ``` -------------------------------- ### Parse Command Arguments Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Parses options specifically for a named command. Use this when dealing with subcommands. ```rust fn parse_command>( name: &str, parser: &mut Parser<'_, S>, ) -> Result where Self: Sized; ``` -------------------------------- ### Function parse_args_or_exit Source: https://docs.rs/gumdrop/latest/gumdrop/fn.parse_args_or_exit.html Parses arguments from the environment. Handles errors by printing to stderr and exiting. Prints help usage if a help option is supplied. ```APIDOC ## Function parse_args_or_exit ### Description Parses arguments from the environment. If an error is encountered, the error is printed to `stderr` and the process will exit with status code `2`. If the user supplies a help option, option usage will be printed to `stderr` and the process will exit with status code `0`. Otherwise, the parsed options are returned. ### Signature ```rust pub fn parse_args_or_exit(style: ParsingStyle) -> T ``` ### Panics If any argument to the process is not valid unicode. ``` -------------------------------- ### Use Custom Parsing Functions for Options Source: https://docs.rs/gumdrop Provide custom parsing logic for option fields using `parse(try_from_str = "...")` for fallible parsing or `parse(from_str = "...")` for infallible parsing. The specified functions must be defined elsewhere in the scope. ```rust use gumdrop::Options; #[derive(Debug, Options)] struct MyOptions { // `try_from_str = "..."` supplies a conversion function that may fail #[options(help = "a hexadecimal value", parse(try_from_str = "parse_hex"))] hex: u32, // `from_str = "..."` supplies a conversion function that always succeeds #[options(help = "a string that becomes uppercase", parse(from_str = "to_upper"))] upper: String, } fn parse_hex(s: &str) -> Result { u32::from_str_radix(s, 16) } fn to_upper(s: &str) -> String { s.to_uppercase() } fn main() { let opts = MyOptions::parse_args_default_or_exit(); println!("{:#?}", opts); } ``` -------------------------------- ### Default Argument Parsing with Exit Handling Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Parses command-line arguments using the default parsing style, with error and help handling. ```APIDOC ## fn parse_args_default_or_exit() -> Self ### Description Parses arguments from the environment, using the default `ParsingStyle`. If an error is encountered, the error is printed to `stderr` and the process will exit with status code `2`. If the user supplies a help option, option usage will be printed to `stderr` and the process will exit with status code `0`. Otherwise, the parsed options are returned. ### Method `Self::parse_args_default_or_exit` ### Parameters None ### Request Example ```rust // Example usage within a struct implementing Options let opts = MyOptions::parse_args_default_or_exit(); ``` ### Response #### Success Response (Self) - Returns an instance of `Self` containing the parsed options. #### Error Response - Prints usage to `stderr` and exits with code `0` if help is requested. - Prints error messages to `stderr` and exits with code `2` if parsing fails. ``` -------------------------------- ### Parser::next_arg Source: https://docs.rs/gumdrop/latest/gumdrop/struct.Parser.html Retrieves the next argument associated with an option. ```APIDOC ## pub fn next_arg(&mut self) -> Option<&'a str> ### Description Returns the next argument to an option, or None if no arguments remain. ### Response #### Success Response (200) - **Option<&'a str>** - The next argument string or None. ``` -------------------------------- ### Gumdrop Derive Macros Source: https://docs.rs/gumdrop/latest/gumdrop/all.html Details on the derive macros available in the gumdrop crate. ```APIDOC ## Derive Macros ### `Options` A derive macro to automatically implement the `Options` trait. ``` -------------------------------- ### Argument Parsing with Exit Handling Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Parses command-line arguments, printing usage and exiting if help is requested, or printing errors and exiting if parsing fails. ```APIDOC ## fn parse_args_or_exit(style: ParsingStyle) -> Self ### Description If the user supplies a help option, option usage will be printed to `stderr` and the process will exit with status code `0`. Otherwise, the parsed options are returned. ### Method `Self::parse_args_or_exit` ### Parameters - `style` (ParsingStyle) - Required - The style to use for parsing arguments. ### Request Example ```rust // Example usage within a struct implementing Options let opts = MyOptions::parse_args_or_exit(ParsingStyle::Sphinx); ``` ### Response #### Success Response (Self) - Returns an instance of `Self` containing the parsed options. #### Error Response - Prints usage to `stderr` and exits with code `0` if help is requested. - Prints error messages to `stderr` and exits with code `2` if parsing fails. ``` -------------------------------- ### Function: parse_args Source: https://docs.rs/gumdrop/latest/gumdrop/fn.parse_args.html Parses command-line arguments into a struct implementing the Options trait. ```APIDOC ## parse_args ### Description Parses arguments from the command line. The first argument (the program name) should be omitted. ### Signature `pub fn parse_args(args: &[String], style: ParsingStyle) -> Result` ### Parameters - **args** (&[String]) - Required - The list of command-line arguments, excluding the program name. - **style** (ParsingStyle) - Required - The parsing style to be applied. ### Returns - **Result** - Returns the parsed struct T on success, or an Error if parsing fails. ``` -------------------------------- ### Parse Arguments with Default Style Source: https://docs.rs/gumdrop/latest/gumdrop/fn.parse_args_default.html Parses arguments from the command line using the default parsing style. The first argument (program name) should be omitted. ```rust pub fn parse_args_default(args: &[String]) -> Result ``` -------------------------------- ### Method: try_into Source: https://docs.rs/gumdrop/latest/gumdrop/struct.Error.html Performs a fallible conversion from one type to another. ```APIDOC ## try_into ### Description Performs the conversion from type T to type U. This is a fallible operation that returns a Result. ### Parameters - **self** (T) - Required - The source object to be converted. ### Response - **Result** - Returns Ok(U) if the conversion succeeds, or an Error if the conversion fails, where Error is defined as >::Error. ``` -------------------------------- ### Parse Arguments with Style Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Parses command-line arguments based on the specified `ParsingStyle`. The first argument (program name) should be omitted. ```rust fn parse_args>( args: &[S], style: ParsingStyle, ) -> Result where Self: Sized; ``` -------------------------------- ### Implement Display for Error Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Formats error variants into human-readable strings for command-line output. ```rust impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::ErrorKind::*; match &self.kind { FailedParse(opt, arg) => write!(f, "invalid argument to option `{}`: {}", opt, arg), FailedParseDefault{option, value, err} => write!(f, "invalid default value for `{}` ({:?}): {}", option, value, err), InsufficientArguments{option, expected, found} => write!(f, "insufficient arguments to option `{}`: expected {}; found {}", option, expected, found), MissingArgument(opt) => write!(f, "missing argument to option `{}`", opt), MissingCommand => f.write_str("missing command name"), MissingRequired(opt) => write!(f, "missing required option `{}`", opt), MissingRequiredCommand => f.write_str("missing required command"), MissingRequiredFree => f.write_str("missing required free argument"), UnexpectedArgument(opt) => write!(f, "option `{}` does not accept an argument", opt), UnexpectedSingleArgument(opt, n) => write!(f, "option `{}` expects {} arguments; found 1", opt, n), UnexpectedFree(arg) => write!(f, "unexpected free argument `{}`", arg), UnrecognizedCommand(cmd) => write!(f, "unrecognized command `{}`", cmd), UnrecognizedLongOption(opt) => write!(f, "unrecognized option `--{}`", opt), UnrecognizedShortOption(opt) => write!(f, "unrecognized option `-{}`", opt), } } } ``` -------------------------------- ### gumdrop::parse_args_default_or_exit Source: https://docs.rs/gumdrop/latest/gumdrop/fn.parse_args_default_or_exit.html Parses arguments from the environment, using the default parsing style. Exits with status code 2 on error, or 0 if help is requested. ```APIDOC ## Function parse_args_default_or_exit ### Description Parses arguments from the environment, using the default parsing style. If an error is encountered, the error is printed to `stderr` and the process will exit with status code `2`. If the user supplies a help option, option usage will be printed to `stderr` and the process will exit with status code `0`. Otherwise, the parsed options are returned. ### Signature ```rust pub fn parse_args_default_or_exit() -> T ``` ### Panics If any argument to the process is not valid unicode. ``` -------------------------------- ### parse_args Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Parses arguments from the command line, excluding the program name. ```APIDOC ## parse_args(args: &[String], style: ParsingStyle) ### Description Parses arguments from the command line. The first argument (the program name) should be omitted. ### Parameters - **args** (&[String]) - Required - The list of command line arguments to parse. - **style** (ParsingStyle) - Required - The parsing style to apply (e.g., AllOptions). ### Response - **Result** - Returns the parsed options or an error. ``` -------------------------------- ### Parse Arguments from Environment (with Exit on Error) Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Parses arguments from the environment with a specified `ParsingStyle`. Errors are printed to stderr and cause process exit. Help options trigger usage display and exit. ```rust /// Parses arguments from the environment. /// /// If an error is encountered, the error is printed to `stderr` and the /// process will exit with status code `2`. /// /// If the user supplies a help option, option usage will be printed to /// `stderr` and the process will exit with status code `0`. /// /// Otherwise, the parsed options are returned. /// /// # Panics /// /// If any argument to the process is not valid unicode. pub fn parse_args_or_exit(style: ParsingStyle) -> T { T::parse_args_or_exit(style) } ``` -------------------------------- ### Opt Enum Trait Implementations Source: https://docs.rs/gumdrop/latest/gumdrop/enum.Opt.html Details the trait implementations for the Opt enum, including Clone, Debug, PartialEq, Copy, Eq, and StructuralPartialEq. ```APIDOC ### Trait Implementations #### impl<'a> Clone for Opt<'a> ##### fn clone(&self) -> Opt<'a> Returns a duplicate of the value. ##### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. #### impl<'a> Debug for Opt<'a> ##### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### impl<'a> PartialEq for Opt<'a> ##### fn eq(&self, other: &Opt<'a>) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. ##### fn ne(&self, other: &Rhs) -> bool Tests for `!=`. #### impl<'a> Copy for Opt<'a> #### impl<'a> Eq for Opt<'a> #### impl<'a> StructuralPartialEq for Opt<'a> ``` -------------------------------- ### Implement From Trait Source: https://docs.rs/gumdrop/latest/gumdrop/enum.Opt.html Allows creating an Opt variant from a value of the same type. This is a simple identity conversion. ```rust fn from(t: T) -> T ``` -------------------------------- ### Implement Subcommand Parsing Source: https://docs.rs/gumdrop/latest/gumdrop/index.html Use the Options derive macro on an enum to define subcommands. Each variant should be a unary tuple containing a struct that implements Options. ```rust use gumdrop::Options; // Define options for the program. #[derive(Debug, Options)] struct MyOptions { // Options here can be accepted with any command (or none at all), // but they must come before the command name. #[options(help = "print help message")] help: bool, #[options(help = "be verbose")] verbose: bool, // The `command` option will delegate option parsing to the command type, // starting at the first free argument. #[options(command)] command: Option, } // The set of commands and the options each one accepts. // // Each variant of a command enum should be a unary tuple variant with only // one field. This field must implement `Options` and is used to parse arguments // that are given after the command name. #[derive(Debug, Options)] enum Command { // Command names are generated from variant names. // By default, a CamelCase name will be converted into a lowercase, // hyphen-separated name; e.g. `FooBar` becomes `foo-bar`. // // Names can be explicitly specified using `#[options(name = "...")]` #[options(help = "show help for a command")] Help(HelpOpts), #[options(help = "make stuff")] Make(MakeOpts), #[options(help = "install stuff")] Install(InstallOpts), } // Options accepted for the `help` command #[derive(Debug, Options)] struct HelpOpts { #[options(free)] free: Vec, } // Options accepted for the `make` command #[derive(Debug, Options)] struct MakeOpts { #[options(free)] free: Vec, #[options(help = "number of jobs", meta = "N")] jobs: Option, } // Options accepted for the `install` command #[derive(Debug, Options)] struct InstallOpts { #[options(help = "target directory")] dir: Option, } fn main() { let opts = MyOptions::parse_args_default_or_exit(); println!("{:#?}", opts); } ``` -------------------------------- ### Parse Arguments or Exit Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Parses command-line arguments using the specified `ParsingStyle` and exits if parsing fails or help is requested. Returns the parsed options. ```rust fn parse_args_or_exit(style: ParsingStyle) -> Self where Self: Sized; ``` -------------------------------- ### Parse Default Arguments or Exit Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Parses command-line arguments using the default parsing style and exits if parsing fails or help is requested. Returns the parsed options. ```rust fn parse_args_default_or_exit() -> Self where Self: Sized; ``` -------------------------------- ### Command-Specific Argument Parsing Source: https://docs.rs/gumdrop/latest/src/gumdrop/lib.rs.html Parses options for a specific named command using a provided parser. ```APIDOC ## fn parse_command>(name: &str, parser: &mut Parser) -> Result ### Description Parses options for the named command using the provided `Parser`. ### Method `Self::parse_command` ### Parameters - `name` (&str) - Required - The name of the command to parse options for. - `parser` (&mut Parser) - Required - A mutable reference to the `Parser` instance. ### Request Example ```rust // Assuming 'parser' is an initialized Parser instance // and 'command_name' is the name of the subcommand match MyOptions::parse_command(command_name, &mut parser) { Ok(opts) => println!("Parsed command options: {:?}", opts), Err(e) => eprintln!("Error parsing command: {}", e), } ``` ### Response #### Success Response (Self) - Returns `Ok(Self)` with the parsed options for the specified command if successful. #### Error Response (Error) - Returns `Err(Error)` if the command is not found or if parsing fails. ``` -------------------------------- ### Implement Any Trait Source: https://docs.rs/gumdrop/latest/gumdrop/enum.Opt.html Allows Opt variants to be treated as any type that is 'static and sized. This is part of Rust's dynamic typing capabilities. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Parse Default Arguments Source: https://docs.rs/gumdrop/latest/gumdrop/trait.Options.html Parses command-line arguments using the default parsing style. Returns a `Result` indicating success or failure. ```rust fn parse_args_default>(args: &[S]) -> Result where Self: Sized; ```