Expand description
Derive-based argument parsing optimized for code size and conformanceto the Fuchsia commandline tools specification
The public API of this library consists primarily of theFromArgsderive and thefrom_env function, which can be used to producea top-levelFromArgs type from the current program’s commandlinearguments.
§Basic Example
useargh::FromArgs;#[derive(FromArgs)]/// Reach new heights.structGoUp {/// whether or not to jump#[argh(switch, short ='j')]jump: bool,/// how high to go#[argh(option)]height: usize,/// an optional nickname for the pilot#[argh(option)]pilot_nickname:Option<String>,}letup: GoUp = argh::from_env();./some_bin --help will then output the following:
Usage: cmdname [-j] --height <height> [--pilot-nickname <pilot-nickname>]Reach new heights.Options: -j, --jump whether or not to jump --height how high to go --pilot-nickname an optional nickname for the pilot --help, help display usage informationThe resulting program can then be used in any of these ways:
./some_bin --height 5./some_bin -j --height 5./some_bin --jump --height 5 --pilot-nickname Wes
Switches, likejump, are optional and will be set to true if provided.
Options, likeheight andpilot_nickname, can be either required,optional, or repeating, depending on whether they are contained in anOption or aVec. Default values can be provided using the#[argh(default = "<your_code_here>")] attribute, and in this case anoption is treated as optional.
useargh::FromArgs;fndefault_height() -> usize {5}#[derive(FromArgs)]/// Reach new heights.#[argh(help_triggers("-h","--help","help"))]structGoUp {/// an optional nickname for the pilot#[argh(option)]pilot_nickname:Option<String>,/// an optional height#[argh(option, default ="default_height()")]height: usize,/// an optional direction which is "up" by default#[argh(option, default ="String::from(\"only up\")")]direction: String,}fnmain() {letup: GoUp = argh::from_env();}Custom option types can be deserialized so long as they implement theFromArgValue trait (automatically implemented for allFromStr types).If more customized parsing is required, you can supply a customfn(&str) -> Result<T, String> using thefrom_str_fn attribute:
#[derive(FromArgs)]/// Goofy thing.structFiveStruct {/// always five#[argh(option, from_str_fn(always_five))]five: usize,}fnalways_five(_value:&str) ->Result<usize, String> {Ok(5)}Positional arguments can be declared using#[argh(positional)].These arguments will be parsed in order of their declaration inthe structure:
useargh::FromArgs;#[derive(FromArgs, PartialEq, Debug)]/// A command with positional arguments.structWithPositional {#[argh(positional)]first: String,}The last positional argument may include a default, or be wrapped inOption orVec to indicate an optional or repeating positional argument.
If your final positional argument has thegreedy option on it, it will consumeany arguments after it as if a-- were placed before the first argument tomatch the greedy positional:
useargh::FromArgs;#[derive(FromArgs, PartialEq, Debug)]/// A command with a greedy positional argument at the end.structWithGreedyPositional {/// some stuff#[argh(option)]stuff:Option<String>,#[argh(positional, greedy)]all_the_rest: Vec<String>,}Now if you pass--stuff Something after a positional argument, it willbe consumed byall_the_rest instead of setting thestuff field.
Note thatall_the_rest won’t be listed as a positional argument in thelong text part of help output (and it will be listed at the end of the usageline as[all_the_rest...]), and it’s up to the caller to append anyextra help output for the meaning of the captured arguments. This is toenable situations where some amount of argument processing needs to happenbefore the rest of the arguments can be interpreted, and shouldn’t be usedfor regular use as it might be confusing.
Subcommands are also supported. To use a subcommand, declare a separateFromArgs type for each subcommand as well as an enum that casesover each command:
#[derive(FromArgs, PartialEq, Debug)]/// Top-level command.structTopLevel {#[argh(subcommand)]nested: MySubCommandEnum,}#[derive(FromArgs, PartialEq, Debug)]#[argh(subcommand)]enumMySubCommandEnum { One(SubCommandOne), Two(SubCommandTwo),}#[derive(FromArgs, PartialEq, Debug)]/// First subcommand.#[argh(subcommand, name ="one")]structSubCommandOne {#[argh(option)]/// how many xx: usize,}#[derive(FromArgs, PartialEq, Debug)]/// Second subcommand.#[argh(subcommand, name ="two")]structSubCommandTwo {#[argh(switch)]/// whether to fooeyfooey: bool,}You can also discover subcommands dynamically at runtime. To do this,declare subcommands as usual and add a variant to the enum with thedynamic attribute. Instead of derivingFromArgs, the value inside thedynamic variant should implementDynamicSubCommand.
#[derive(FromArgs, PartialEq, Debug)]/// Top-level command.structTopLevel {#[argh(subcommand)]nested: MySubCommandEnum,}#[derive(FromArgs, PartialEq, Debug)]#[argh(subcommand)]enumMySubCommandEnum { Normal(NormalSubCommand),#[argh(dynamic)]Dynamic(Dynamic),}#[derive(FromArgs, PartialEq, Debug)]/// Normal subcommand.#[argh(subcommand, name ="normal")]structNormalSubCommand {#[argh(option)]/// how many xx: usize,}/// Dynamic subcommand.#[derive(PartialEq, Debug)]structDynamic { name: String}implDynamicSubCommandforDynamic {fncommands() ->&'static[&'staticCommandInfo] {staticRET: OnceCell<Vec<&'staticCommandInfo>> = OnceCell::new(); RET.get_or_init(|| {letmutcommands = Vec::new();// argh needs the `CommandInfo` structs we generate to be valid // for the static lifetime. We can allocate the structures on // the heap with `Box::new` and use `Box::leak` to get a static // reference to them. We could also just use a constant // reference, but only because this is a synthetic example; the // point of using dynamic commands is to have commands you // don't know about until runtime!commands.push(&*Box::leak(Box::new(CommandInfo { name:"dynamic_command", description:"A dynamic command", }))); commands }) }fntry_redact_arg_values( command_name:&[&str], args:&[&str], ) ->Option<Result<Vec<String>, EarlyExit>> {forcommandinSelf::commands() {ifcommand_name.last() ==Some(&command.name) {// Process arguments and redact values here.if!args.is_empty() {returnSome(Err("Our example dynamic command never takes arguments!".to_string().into())); }returnSome(Ok(Vec::new())) } }None}fntry_from_args(command_name:&[&str], args:&[&str]) ->Option<Result<Self, EarlyExit>> {forcommandinSelf::commands() {ifcommand_name.last() ==Some(&command.name) {if!args.is_empty() {returnSome(Err("Our example dynamic command never takes arguments!".to_string().into())); }returnSome(Ok(Dynamic { name: command.name.to_string() })) } }None}}Programs that are run from an environment such as cargo may find ituseful to have positional arguments present in the structure butomitted from the usage output. This can be accomplished by addingthehidden_help attribute to that argument:
#[derive(FromArgs)]/// Cargo argumentsstructCargoArgs {// Cargo puts the command name invoked into the first argument, // so we don't want this argument to show up in the usage text.#[argh(positional, hidden_help)]command: String,/// an option used for internal debugging#[argh(option, hidden_help)]internal_debugging: String,#[argh(positional)]real_first_arg: String,}Structs§
- Early
Exit - Information to display to the user about why a
FromArgsconstruction exited early. - Error
Code Info - Information about a documented error code.
- Flag
Info - Information about a flag or option.
- Positional
Info - Information about positional arguments
Enums§
- Flag
Info Kind - The kind of flags.
- Optionality
- The optionality defines the requirements relatedto the presence of the argument on the command line.
Traits§
- Args
Info - Structured information about the command line arguments.
- Dynamic
SubCommand - Trait implemented by values returned from a dynamic subcommand handler.
- Flag
- A type which can be the receiver of a
Flag. - From
ArgValue - Types which can be constructed from a single commandline value.
- From
Args - Types which can be constructed from a set of commandline arguments.
- SubCommand
- A
FromArgsimplementation that represents a single subcommand. - SubCommands
- A
FromArgsimplementation that can parse into one or more subcommands. - TopLevel
Command - A top-level
FromArgsimplementation that is not a subcommand.
Functions§
- cargo_
from_ env - Create a
FromArgstype from the current process’senv::args. - from_
env - Create a
FromArgstype from the current process’senv::args.
Type Aliases§
- Command
Info - Information about a particular command used for output.
- Command
Info With Args - Information about the command including the options and arguments.
- SubCommand
Info - Information about a subcommand.