### Define Complex Help Output with Examples Source: https://github.com/google/argh/blob/master/README.md Use this to define a complex help output that includes an Examples section. The `{command_name}` placeholder can be used within the description and example fields. ```rust #[derive(FromArgs, Debug)] #[argh( description = "{command_name} is a tool to reach new heights.\n\n Start exploring new heights:\n\n \u{00A0} {command_name} --height 5 jump\n ", example = "\n {command_name} --height 5\n {command_name} --height 5 j\n {command_name} --height 5 --pilot-nickname Wes jump" )] pub struct CliArgs { /// how high to go #[argh(option)] height: usize, /// an optional nickname for the pilot #[argh(option)] pilot_nickname: Option, /// command to execute #[argh(subcommand)] pub command: Command, } ``` -------------------------------- ### Option and Flag Completion Example Source: https://github.com/google/argh/blob/master/_autodocs/09-completion-generators.md All options and switches are available for completion. This example demonstrates completing options for the 'migrate' subcommand of 'migration-tool'. ```shell $ migration-tool migrate -- --database --steps --verbose --help ``` -------------------------------- ### Customize Help Messages with Examples Source: https://github.com/google/argh/blob/master/_autodocs/10-usage-examples.md Configure detailed help messages, including descriptions and usage examples, using attributes like `description`, `help_triggers`, and `example`. The `{command_name}` placeholder is automatically replaced. ```rust use argh::FromArgs; #[derive(FromArgs)] #[argh( description = "A comprehensive tool for data processing.", help_triggers = "-h", "--help", "-?", "help", example = " Quickstart:\n {command_name} --help\n\n Basic usage:\n {command_name} --input data.csv --output results.json" )] struct DataTool { #[argh(option)] input: String, #[argh(option)] output: String, } fn main() { let tool: DataTool = argh::from_env(); println!("Processing {} → {}", tool.input, tool.output); } ``` -------------------------------- ### Struct-Level Example Attribute Source: https://github.com/google/argh/blob/master/_autodocs/07-derive-macro-attributes.md Provide usage examples in the help output using `#[argh(example = "...")]`. The string literal can use the `{command_name}` placeholder and should use `\n` for newlines. ```rust #[derive(FromArgs)] #[argh( description = "My tool", example = " {command_name} --input file.txt\n {command_name} --input data.csv --output results.csv" )] struct MyCmd { // fields } ``` ```rust #[derive(FromArgs)] #[argh(example = "\Run a build:\n {command_name} build\n\nRun tests:\n {command_name} test --filter unit\n\nRun in release mode:\n {command_name} build --release")] struct BuildTool { #[argh(subcommand)] cmd: Commands, } ``` -------------------------------- ### Usage Examples Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt A collection of runnable code examples demonstrating various use cases and features of the ARGH library. ```APIDOC ## Usage Examples ### Description Illustrative examples showcasing how to use ARGH for different CLI application scenarios. ### Example Categories - Simple CLI (word counter) - Server configuration with defaults - Git-like subcommands - Custom parsing with `FromArgValue` - Complex positional arguments - Greedy positional arguments - Enum values with `FromArgValue` - Error handling with `try_from_env` - Feature combinations - Cargo integration - Help customization ### Quantity - 50+ runnable code examples ``` -------------------------------- ### Complete Plugin System Example Source: https://github.com/google/argh/blob/master/_autodocs/06-dynamic-subcommands.md This example demonstrates a full application with a plugin system using dynamic subcommands. It shows how to define built-in commands alongside dynamically loaded plugins, including command discovery and argument parsing. ```rust use argh::{CommandInfo, DynamicSubCommand, EarlyExit, FromArgs}; use std::sync::LazyLock; #[derive(FromArgs)] /// Application with plugin system. struct App { #[argh(subcommand)] command: Command, } #[derive(FromArgs)] #[argh(subcommand)] enum Command { /// built-in commands Builtin(BuiltinCmd), /// dynamically loaded plugins #[argh(dynamic)] Plugin(PluginCommand), } #[derive(FromArgs)] /// Built-in command. #[argh(subcommand, name = "builtin")] struct BuiltinCmd { /// something #[argh(option)] value: String, } /// Dynamic plugin command. #[derive(Debug)] struct PluginCommand { name: String, args: Vec, } impl DynamicSubCommand for PluginCommand { fn commands() -> &'static [&'static CommandInfo] { static PLUGINS: LazyLock> = LazyLock::new(|| { // Simulate loading plugins from disk let mut cmds = Vec::new(); // Add each discovered plugin cmds.push(&*Box::leak(Box::new(CommandInfo { name: "compress", short: &'c', description: "Compression plugin", }))); cmds.push(&*Box::leak(Box::new(CommandInfo { name: "encrypt", short: &'e', description: "Encryption plugin", }))); cmds }); &PLUGINS } fn try_redact_arg_values( command_name: &[&str], args: &[&str], ) -> Option, EarlyExit>> { let plugin_name = command_name.last()?; // Check if it's a known plugin if !Self::commands().iter().any(|c| &c.name == plugin_name) { return None; } // Redact all arguments let mut result = vec![command_name.join(" ")]; for arg in args { if arg.starts_with('-') { result.push(arg.to_string()); } else { // Redact values result.push("VALUE".to_string()); } } Some(Ok(result)) } fn try_from_args( command_name: &[&str], args: &[&str], ) -> Option> { let plugin_name = match command_name.last() { Some(name) => *name, None => return None, }; // Check if it's a known plugin if !Self::commands().iter().any(|c| c.name == plugin_name) { return None; } Some(Ok(PluginCommand { name: plugin_name.to_string(), args: args.iter().map(|s| s.to_string()).collect(), })) } } fn main() { let app: App = argh::from_env(); match app.command { Command::Builtin(cmd) => { println!("Builtin: {}", cmd.value); } Command::Plugin(plugin) => { println!("Plugin '{}' with args: {:?}", plugin.name, plugin.args); } } } ``` -------------------------------- ### Example Usage of SubCommandInfo Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md Illustrates how to instantiate the SubCommandInfo struct with specific subcommand details. ```rust use argh::SubCommandInfo; let sub = SubCommandInfo { name: "build", command: CommandInfoWithArgs { name: "build", short: &'b', description: "Build the project", examples: &[], flags: &[], notes: &[], commands: vec![], positionals: &[], error_codes: &[], }, }; ``` -------------------------------- ### Example CommandInfoWithArgs Initialization Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md Demonstrates initializing a CommandInfoWithArgs structure for a basic command-line application. ```rust use argh::{CommandInfoWithArgs, FlagInfo, PositionalInfo, SubCommandInfo}; let cmd_info = CommandInfoWithArgs { name: "myapp", short: &'\0', description: "A command-line application", examples: &["myapp --help", "myapp build --verbose"], flags: &[], notes: &[], commands: vec![], positionals: &[], error_codes: &[], }; ``` -------------------------------- ### Usage Examples Source: https://github.com/google/argh/blob/master/_autodocs/README.md A collection of practical usage examples demonstrating how to use Argh for various CLI application scenarios, from simple tools to complex configurations. ```APIDOC ## Usage Examples ### Description Illustrative examples showcasing various use cases and patterns for the Argh library. ### Scenarios Covered - Simple CLI applications (e.g., word counter). - Server configuration with default values. - Applications with Git-like subcommands. - Custom value parsing. - Complex positional arguments, including greedy ones. - Enum-based options. - Error handling patterns. - Combinations of features. - Cargo integration examples. ``` -------------------------------- ### Example Usage of ArgsInfo Trait Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md Demonstrates how to use the ArgsInfo trait with a derived implementation to get command metadata and print it. ```rust use argh::{FromArgs, ArgsInfo}; #[derive(FromArgs, ArgsInfo)] /// My application struct MyApp { #[argh(option)] input: String, } fn main() { let info = MyApp::get_args_info(); println!("Command: {}", info.name); println!("Description: {}", info.description); } ``` -------------------------------- ### Define Complex Help Output with Examples in Rust Source: https://github.com/google/argh/blob/master/argh/README.md Use the `argh` crate to define a complex help output including an examples section. The `{command_name}` placeholder can be used within the description and example fields. ```rust #[derive(FromArgs, Debug)] #[argh( description = "{command_name} is a tool to reach new heights.\n\n Start exploring new heights:\n\n \u{00A0} {command_name} --height 5 jump\n ", example = " {command_name} --height 5\n {command_name} --height 5 j\n {command_name} --height 5 --pilot-nickname Wes jump" )] pub struct CliArgs { /// how high to go #[argh(option)] height: usize, /// an optional nickname for the pilot #[argh(option)] pilot_nickname: Option, /// command to execute #[argh(subcommand)] pub command: Command, } ``` -------------------------------- ### Server Configuration Usage Examples Source: https://github.com/google/argh/blob/master/_autodocs/10-usage-examples.md Illustrates how to invoke the server configuration with different command-line arguments, demonstrating default values and option overrides. ```bash $ ./server -p 3000 -vvv --root /var/www Serving /var/www on 127.0.0.1:3000 SSL: false Verbosity: 3 $ ./server --ssl --cert cert.pem --port 443 Serving . on 127.0.0.1:443 SSL: true Verbosity: 0 ``` -------------------------------- ### Subcommand Completion Example Source: https://github.com/google/argh/blob/master/_autodocs/09-completion-generators.md When the command structure has subcommands, completion scripts suggest them. This example shows subcommand suggestions for 'migration-tool'. ```shell $ migration-tool migrate -- Apply pending migrations rollback -- Rollback applied migrations status -- List migration status ``` -------------------------------- ### Install Nushell Completion Source: https://github.com/google/argh/blob/master/_autodocs/09-completion-generators.md Instructions for installing Nushell completion scripts by appending the generated script to the Nushell environment configuration file. ```bash # Add to ~/.config/nushell/env.nu ./myapp >> ~/.config/nushell/env.nu ``` -------------------------------- ### Install Fish Shell Completion Source: https://github.com/google/argh/blob/master/_autodocs/09-completion-generators.md Instructions for installing Fish shell completion scripts by generating the script and placing it in the appropriate directory. ```bash # Generate completion ./myapp > ~/.config/fish/completions/myapp.fish # Reload fish fish -c "complete -C myapp" ``` -------------------------------- ### Example CommandInfo Constants Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md Illustrates the creation of constants using the CommandInfo structure for 'build' and 'test' commands. ```rust use argh::CommandInfo; const BUILD_CMD: CommandInfo = CommandInfo { name: "build", short: &'b', description: "Build the project", }; const TEST_CMD: CommandInfo = CommandInfo { name: "test", short: &'t', description: "Run unit tests", }; ``` -------------------------------- ### Display Custom Help Message Source: https://github.com/google/argh/blob/master/_autodocs/10-usage-examples.md Shows the output of the customized help message for the `DataTool` example. Demonstrates how the defined `description`, `help_triggers`, and `example` attributes are rendered. ```bash $ ./data-tool -h Usage: data-tool --input --output A comprehensive tool for data processing. Options: --input input file path --output output file path -h, -?, --help, help display usage information Examples: Quickstart: data-tool --help Basic usage: data-tool --input data.csv --output results.json ``` -------------------------------- ### Bash Script for Installing Completion Files Source: https://github.com/google/argh/blob/master/_autodocs/09-completion-generators.md This bash script automates the generation and installation of shell completion files for the `migration-tool` binary. It iterates through supported shells and outputs the completion scripts to a specified directory. ```bash #!/bin/bash # install-completions.sh BINARY_PATH="./migration-tool" COMPLETIONS_DIR="${1:-.}" # Generate and install for each shell _MIGRATION_TOOL_COMPLETE=bash $BINARY_PATH > "$COMPLETIONS_DIR/migration-tool.bash" _MIGRATION_TOOL_COMPLETE=fish $BINARY_PATH > "$COMPLETIONS_DIR/migration-tool.fish" _MIGRATION_TOOL_COMPLETE=zsh $BINARY_PATH > "$COMPLETIONS_DIR/_migration-tool" _MIGRATION_TOOL_COMPLETE=nushell $BINARY_PATH > "$COMPLETIONS_DIR/migration-tool-completions.nu" echo "Completions installed to $COMPLETIONS_DIR" ``` -------------------------------- ### Example FlagInfo Instantiations Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md Demonstrates how to create instances of the `FlagInfo` struct for a boolean switch flag and a required option flag. ```rust use argh::{FlagInfo, FlagInfoKind, Optionality}; const VERBOSE_FLAG: FlagInfo = FlagInfo { kind: FlagInfoKind::Switch, optionality: Optionality::Optional, long: "verbose", short: Some('v'), description: "Enable verbose output", hidden: false, }; const OUTPUT_OPTION: FlagInfo = FlagInfo { kind: FlagInfoKind::Option { arg_name: "FILE" }, optionality: Optionality::Required, long: "output", short: Some('o'), description: "Output file path", hidden: false, }; ``` -------------------------------- ### Complete CLI Example with Derive Macros Source: https://github.com/google/argh/blob/master/_autodocs/07-derive-macro-attributes.md This example demonstrates a full CLI application structure using `argh`'s derive macros. It defines a main struct for the tool, an enum for subcommands, and specific structs for each subcommand's arguments. Use this pattern to build complex CLIs with nested commands and options. ```rust use argh::FromArgs; #[derive(FromArgs)] /// Build system utility. #[argh( description = "A build tool for managing projects", example = " {command_name} build\n\n {command_name} test --filter unit\n\n {command_name} clean" )] struct BuildTool { /// verbosity level #[argh(switch, short = 'v')] verbose: bool, #[argh(subcommand)] command: Command, } #[derive(FromArgs)] #[argh(subcommand)] enum Command { /// Compile the project #[argh(subcommand, name = "build", short = 'b')] Build(BuildCmd), /// Run tests #[argh(subcommand, name = "test", short = 't')] Test(TestCmd), } #[derive(FromArgs)] /// Build configuration. #[argh(subcommand, name = "build")] struct BuildCmd { /// optimization level #[argh(option, short = 'O', default = "0")] opt_level: u8, /// additional targets #[argh(option)] target: Vec, } #[derive(FromArgs)] /// Test configuration. #[argh(subcommand, name = "test")] struct TestCmd { /// filter tests by name #[argh(option)] filter: Option, /// test files to run #[argh(positional)] files: Vec, } ``` -------------------------------- ### Bash Completion Installation Source: https://github.com/google/argh/blob/master/_autodocs/09-completion-generators.md Instructions for installing the generated Bash completion script. This involves either saving the script to a specific directory or appending it to the shell's configuration file. ```bash # Generate and save completion script ./myapp > ~/.bash_completion.d/myapp # Or add to ~/.bashrc myapp >> ~/.bashrc ``` -------------------------------- ### Git-like Subcommands Usage Examples Source: https://github.com/google/argh/blob/master/_autodocs/10-usage-examples.md Demonstrates invoking the Git-like command-line interface with different subcommands and arguments, showing how to handle positional arguments, options, and global flags. ```bash $ ./vcs init /tmp/repo Initializing repo at /tmp/repo Bare: false $ ./vcs -v clone https://example.com/repo.git myrepo Verbose mode enabled Cloning https://example.com/repo.git to myrepo $ ./vcs commit -m "Initial commit" --author "Alice " Committing: Initial commit Author: Alice ``` -------------------------------- ### Example Initialization of PositionalInfo Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md Demonstrates how to create instances of PositionalInfo for required and repeating positional arguments, specifying their properties. ```rust use argh::{PositionalInfo, Optionality}; const SOURCE_FILE: PositionalInfo = PositionalInfo { name: "SOURCE", description: "Source file to process", optionality: Optionality::Required, hidden: false, }; const EXTRA_FILES: PositionalInfo = PositionalInfo { name: "FILES", description: "Additional files", optionality: Optionality::Repeating, hidden: false, }; ``` -------------------------------- ### Install Zsh Shell Completion Source: https://github.com/google/argh/blob/master/_autodocs/09-completion-generators.md Instructions for installing Zsh shell completion scripts by generating the script and placing it in the Zsh completions directory. ```bash # Generate completion ./myapp > ~/.zsh/completions/_myapp # Zsh will auto-discover files in ~/.zsh/completions ``` -------------------------------- ### Example ErrorCodeInfo Constants Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md Provides examples of defining constants using the ErrorCodeInfo structure for common error scenarios. ```rust use argh::ErrorCodeInfo; const FILE_NOT_FOUND_ERR: ErrorCodeInfo = ErrorCodeInfo { code: 2, description: "Input file not found", }; const PERMISSION_ERR: ErrorCodeInfo = ErrorCodeInfo { code: 13, description: "Permission denied", }; ``` -------------------------------- ### Short Form Flag Completion Example Source: https://github.com/google/argh/blob/master/_autodocs/09-completion-generators.md Short-form flags are also completed. This example shows short-form flag completion for 'migration-tool'. ```shell $ migration-tool - -d -- database -v -- verbose -h -- help ``` -------------------------------- ### FromEnv Function Example Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Shows how to use the `from_env` function for automatic error handling when parsing arguments. ```Rust use argh::FromArgs; /// My awesome binary #[derive(FromArgs)] struct Args { /// Input file #[argh(positional)] input: String, /// Output file #[argh(positional)] output: String, } fn main() { let args: Args = argh::from_env(); // ... use args.input and args.output } ``` -------------------------------- ### Serializing Command Metadata to JSON Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md An example demonstrating how to obtain command information using ArgsInfo and then serialize it into a pretty-printed JSON string using serde_json. ```rust use argh::ArgsInfo; #[derive(FromArgs, ArgsInfo)] struct App { #[argh(option)] input: String, } let info = App::get_args_info(); let json = serde_json::to_string_pretty(&info).unwrap(); println!("{}", json); ``` -------------------------------- ### CargoFromEnv Function Example Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Demonstrates using `cargo_from_env` for parsing arguments within a Cargo context. ```Rust use argh::FromArgs; /// My awesome binary #[derive(FromArgs)] struct Args { /// A required argument #[argh(positional)] required_arg: String, } fn main() { let args: Args = argh::cargo_from_env(); // ... use args.required_arg } ``` -------------------------------- ### Complex Help Description with Examples Source: https://github.com/google/argh/blob/master/argh_derive/README.md Defines a struct with an advanced help message that includes a command name placeholder and a detailed examples section. This is useful for tools with subcommands or complex argument structures. ```rust #[derive(FromArgs, Debug)] #[argh( description = "{command_name} is a tool to reach new heights.\n\n Start exploring new heights:\n\n \u{00A0} {command_name} --height 5 jump\n ", example = "\ {command_name} --height 5\n {command_name} --height 5 j\n {command_name} --height 5 --pilot-nickname Wes jump" )] pub struct CliArgs { /// how high to go #[argh(option)] height: usize, /// an optional nickname for the pilot #[argh(option)] pilot_nickname: Option, /// command to execute #[argh(subcommand)] pub command: Command, } ``` -------------------------------- ### Greedy Positional Arguments Usage Examples Source: https://github.com/google/argh/blob/master/_autodocs/10-usage-examples.md Shows how to invoke the `exec` command with different arguments and the resulting parsed output. ```bash $ ./exec echo hello -n world Program: echo Args: ["hello", "-n", "world"] $ ./exec ls -la /home/user Program: ls Args: ["-la", "/home/user"] ``` -------------------------------- ### Shell Completion Generator Example (Bash) Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Shows how to implement a shell completion generator for Bash using the `Generator` trait. ```Rust use argh::completion::Generator; struct BashGenerator; impl Generator for BashGenerator { fn generate(&self, command_name: &str, args_info: &argh::ArgsInfo) -> String { // Implementation to generate Bash completion script format!("# Bash completion for {}", command_name) } } // Usage: // let generator = BashGenerator; // let completion_script = generator.generate("my_cli", &Cli::args_info()); // println!("{}", completion_script); ``` -------------------------------- ### TryFromEnv Function Example Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Illustrates using `try_from_env` for result-based error handling, allowing custom error management. ```Rust use argh::{FromArgs, FromEnvError}; /// My awesome binary #[derive(FromArgs)] struct Args { /// Verbose output #[argh(switch, short = 'v')] verbose: bool, } fn main() { match argh::try_from_env::() { Ok(args) => { // ... use args if args.verbose { println!("Verbose mode enabled"); } } Err(e) => { // Handle the error, e.g., print usage and exit eprintln!("{}", e); std::process::exit(1); } } } ``` -------------------------------- ### ArgsInfo Trait Example Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Demonstrates the `ArgsInfo` trait for generating metadata about commands and arguments, useful for help generation and shell completions. ```Rust use argh::{ArgsInfo, FromArgs}; /// A simple command-line tool #[derive(FromArgs, ArgsInfo)] struct Cli { /// Input file path #[argh(positional)] input: String, /// Verbose output #[argh(switch, short = 'v')] verbose: bool, } fn main() { let args_info = Cli::args_info(); println!("Command: {}", args_info.name); println!("Description: {}", args_info.description); // ... iterate through args_info.flags, args_info.positionals, etc. } ``` -------------------------------- ### Archive Management Tool with Subcommands Source: https://github.com/google/argh/blob/master/_autodocs/10-usage-examples.md This example defines a command-line tool for archive management using Argh. It supports 'create' and 'extract' subcommands, each with its own set of options and arguments. The 'create' command allows specifying compression, output file, and input files, while the 'extract' command takes a source archive and an optional destination directory. Verbose mode is also supported. ```rust use argh::{FromArgs, FromArgValue}; #[derive(FromArgValue, Debug)] enum Compression { None, Gzip, Bzip2, } #[derive(FromArgs)] /// Archive management tool. #[argh( description = "{command_name} creates and extracts archive files.", example = " {command_name} create --compression gzip output.tar.gz file1 file2\n {command_name} extract --source archive.tar.gz" )] struct Archive { /// increase verbosity #[argh(switch, short = 'v')] verbose: bool, #[argh(subcommand)] command: Command, } #[derive(FromArgs)] #[argh(subcommand)] enum Command { /// Create a new archive #[argh(subcommand, name = "create")] Create(CreateCmd), /// Extract an archive #[argh(subcommand, name = "extract")] Extract(ExtractCmd), } #[derive(FromArgs)] #[argh(subcommand, name = "create")] struct CreateCmd { /// compression method #[argh(option, default = "Compression::None")] compression: Compression, /// output file path #[argh(option, short = 'o')] output: String, /// files to archive #[argh(positional)] files: Vec, } #[derive(FromArgs)] #[argh(subcommand, name = "extract")] struct ExtractCmd { /// source archive file #[argh(option, short = 's')] source: String, /// destination directory #[argh(option, short = 'd', default = "String::from(\".\")")] destination: String, } fn main() { let archive: Archive = argh::from_env(); match archive.command { Command::Create(create) => { println!("Creating archive: {}", create.output); println!("Compression: {:?}", create.compression); println!("Files: {:?}", create.files); if archive.verbose { println!("(Verbose mode)"); } } Command::Extract(extract) => { println!("Extracting: {}", extract.source); println!("To: {}", extract.destination); } } } ``` -------------------------------- ### FromArgs Trait Example Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Demonstrates the basic usage of the FromArgs trait for parsing command-line arguments. ```Rust use argh::FromArgs; /// My awesome binary #[derive(FromArgs)] struct Args { /// Print version and exit #[argh(switch, short = 'V')] verbose: bool, } fn main() { let args: Args = argh::from_env(); if args.verbose { println!("Version 1.0.0"); } } ``` -------------------------------- ### Argument Parsing Help Output Source: https://github.com/google/argh/blob/master/argh/README.md The `argh` crate automatically generates help messages based on struct documentation and attributes. This example shows the expected output for the `GoUp` struct. ```text Usage: cmdname [-j] --height [--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 information ``` -------------------------------- ### DynamicSubCommand Trait Example Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Illustrates the `DynamicSubCommand` trait for implementing dynamic subcommands, allowing for runtime discovery of commands. ```Rust use argh::{DynamicSubCommand, FromArgs, FromEnvError}; use std::collections::HashMap; struct MyCommand { name: String, } impl DynamicSubCommand for MyCommand { fn commands() -> HashMap> { let mut commands = HashMap::new(); commands.insert("hello".to_string(), Box::new(MyCommand { name: "hello".to_string() })); commands } fn try_from_args(command_name: &str, args: &[&str]) -> Result { if command_name == "hello" { Ok(MyCommand { name: command_name.to_string() }) } else { Err(FromEnvError::UnknownCommand(command_name.to_string())) } } } fn main() { // Usage would involve a top-level struct deriving FromArgs // that includes a field typed with a trait bound for DynamicSubCommand. // Example: // #[derive(FromArgs)] // struct TopLevel { // #[argh(subcommand)] // cmd: ::BoxedType, // } // let args: TopLevel = argh::from_env(); } ``` -------------------------------- ### Generate Bash Completion Script Source: https://github.com/google/argh/blob/master/_autodocs/09-completion-generators.md Example of how to use the Bash generator to create a completion script for a sample Argh application. This script is typically printed to stdout and sourced by the shell. ```rust use argh::{FromArgs, ArgsInfo}; use argh_complete::bash::Bash; use argh_complete::Generator; #[derive(FromArgs, ArgsInfo)] struct MyApp { #[argh(option)] input: String, #[argh(switch, short = 'v')] verbose: bool, } fn main() { if std::env::var("GENERATE_BASH_COMPLETIONS").is_ok() { let cmd_info = MyApp::get_args_info(); let script = Bash::generate("myapp", &cmd_info); println!("{}", script); } } ``` -------------------------------- ### Example Usage of Optionality Enum Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md Illustrates how to use the Optionality enum variants to define argument behaviors like required, optional, repeating, and greedy. ```rust use argh::Optionality; // Required argument: --input FILE Optionality::Required // Optional argument: [--output FILE] Optionality::Optional // Repeating argument: [--include DIR ...] Optionality::Repeating // Greedy positional: FILES... Optionality::Greedy ``` -------------------------------- ### Implementing DynamicSubCommand for DynamicHandler Source: https://github.com/google/argh/blob/master/_autodocs/06-dynamic-subcommands.md Example implementation of the DynamicSubCommand trait. This registers two plugin commands, 'plugin1' and 'plugin2', with short aliases and descriptions. The actual argument parsing logic is left unimplemented. ```rust use argh::{CommandInfo, DynamicSubCommand, EarlyExit}; use std::sync::LazyLock; struct DynamicHandler { command_name: String, } impl DynamicSubCommand for DynamicHandler { fn commands() -> &'static [&'static CommandInfo] { static RET: LazyLock> = LazyLock::new(|| { vec![ &*Box::leak(Box::new(CommandInfo { name: "plugin1", short: &'p', description: "First plugin command", })), &*Box::leak(Box::new(CommandInfo { name: "plugin2", short: &'q', description: "Second plugin command", })), ] }); &RET } fn try_redact_arg_values( command_name: &[&str], args: &[&str], ) -> Option, EarlyExit>> { // Implementation below unimplemented!() } fn try_from_args( command_name: &[&str], args: &[&str], ) -> Option> { // Implementation below unimplemented!() } } ``` -------------------------------- ### Configure Server with Options Source: https://github.com/google/argh/blob/master/_autodocs/10-usage-examples.md Define and parse command-line options for a server configuration, including host, port, SSL, certificate path, verbosity, and root directory. Handles default values and conditional requirements like the certificate path when SSL is enabled. ```rust use argh::FromArgs; #[derive(FromArgs)] /// Start a development web server. struct ServerConfig { /// server binding address (default: localhost) #[argh(option, default = "String::from(\"127.0.0.1\")")] host: String, /// listening port (default: 8080) #[argh(option, short = 'p', default = "8080")] port: u16, /// enable SSL/TLS #[argh(switch)] ssl: bool, /// certificate file path (required if --ssl) #[argh(option)] cert: Option, /// verbosity level (-v, -vv, -vvv) #[argh(switch, short = 'v')] verbosity: u8, /// root directory to serve #[argh(option)] root: Option, } fn main() { let config: ServerConfig = argh::from_env(); if config.ssl && config.cert.is_none() { eprintln!("Error: --cert required when using --ssl"); std::process::exit(1); } let root = config.root.as_deref().unwrap_or("."); println!("Serving {} on {}:{}", root, config.host, config.port); println!("SSL: {}", config.ssl); println!("Verbosity: {}", config.verbosity); } ``` -------------------------------- ### Basic CLI with Option and Switch Source: https://github.com/google/argh/blob/master/_autodocs/INDEX.md Demonstrates a basic command-line interface structure using Argh, defining an input option and a verbose switch. Use this for simple CLIs with required string inputs and optional boolean flags. ```rust #[derive(FromArgs)] struct Args { #[argh(option)] input: String, #[argh(switch, short = 'v')] verbose: bool, } let args = argh::from_env(); ``` -------------------------------- ### FromArgValue Trait Example Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Shows how to implement and use the `FromArgValue` trait for custom argument parsing. ```Rust use argh::FromArgValue; use std::str::FromStr; #[derive(Debug, PartialEq)] struct MyInt(i32); impl FromArgValue for MyInt { fn from_arg_value(value: &str) -> Result { Ok(MyInt(value.parse().map_err(|_| "Invalid integer format")?)) } } // Usage in a struct: // #[derive(FromArgs)] // struct Args { // #[argh(option)] // value: MyInt, // } ``` -------------------------------- ### Plugin System with Dynamic Subcommands Source: https://github.com/google/argh/blob/master/_autodocs/INDEX.md Demonstrates the implementation of a plugin system using Argh's dynamic subcommand feature. This allows for extensible CLIs where plugins can register their own commands. ```rust #[argh(dynamic)] Dynamic(PluginHandler), impl DynamicSubCommand for PluginHandler { fn commands() -> &'static [&'static CommandInfo] { } fn try_from_args(...) -> Option> { } } ``` -------------------------------- ### Derive Macro Attributes Example Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Illustrates various struct-level and field-level attributes for customizing argument parsing with `argh_derive`. ```Rust use argh::FromArgs; /// A tool with various argument types #[derive(FromArgs)] struct Cli { /// Enable verbose output #[argh(switch, short = 'v', description = "Increase output verbosity")] verbose: bool, /// Set the output file path #[argh(option, short = 'o', default = "\"output.txt\"".to_string(), description = "Path to the output file")] output: String, /// Input files to process #[argh(positional, greedy, description = "One or more input files")] inputs: Vec, /// Subcommand to execute #[argh(subcommand)] command: SubCommand, } #[derive(FromArgs)] enum SubCommand { Build(BuildArgs), Run(RunArgs), } #[derive(FromArgs)] struct BuildArgs { /// Build configuration profile #[argh(option, default = "\"debug\"".to_string())] profile: String, } #[derive(FromArgs)] struct RunArgs { /// Port to listen on #[argh(option, short = 'p', default = "8080")] port: u16, } ``` -------------------------------- ### Enum Values Usage Examples Source: https://github.com/google/argh/blob/master/_autodocs/10-usage-examples.md Demonstrates successful parsing of enum values and the error message for an invalid enum value. ```bash $ ./converter --input data.json --output yaml Converting from data.json to Yaml $ ./converter --input data.json --output invalid Error parsing option '--output' with value 'invalid': expected "json" or "yaml" or "toml" ``` -------------------------------- ### Implement Git-like Subcommands Source: https://github.com/google/argh/blob/master/_autodocs/10-usage-examples.md Structure a command-line application with multiple subcommands (init, clone, commit) similar to Git. Supports global options and subcommand-specific arguments and switches. ```rust use argh::FromArgs; #[derive(FromArgs)] /// Version control system. struct Vcs { /// global verbosity #[argh(switch, short = 'v')] verbose: bool, #[argh(subcommand)] command: Command, } #[derive(FromArgs)] #[argh(subcommand)] enum Command { /// Initialize a repository #[argh(subcommand, name = "init", short = 'i')] Init(InitCmd), /// Clone a repository #[argh(subcommand, name = "clone", short = 'c')] Clone(CloneCmd), /// Commit changes #[argh(subcommand, name = "commit", short = 'c')] Commit(CommitCmd), } #[derive(FromArgs)] #[argh(subcommand, name = "init")] struct InitCmd { /// bare repository (no working directory) #[argh(switch)] bare: bool, /// repository path #[argh(positional)] path: String, } #[derive(FromArgs)] #[argh(subcommand, name = "clone")] struct CloneCmd { /// repository URL to clone #[argh(positional)] url: String, /// destination directory (optional) #[argh(positional)] directory: Option, } #[derive(FromArgs)] #[argh(subcommand, name = "commit")] struct CommitCmd { /// commit message #[argh(option, short = 'm')] message: String, /// author name #[argh(option)] author: Option, /// amend previous commit #[argh(switch)] amend: bool, } fn main() { let vcs: Vcs = argh::from_env(); if vcs.verbose { println!("Verbose mode enabled"); } match vcs.command { Command::Init(init) => { println!("Initializing repo at {}", init.path); println!("Bare: {}", init.bare); } Command::Clone(clone) => { let dir = clone.directory.as_deref().unwrap_or(&clone.url); println!("Cloning {} to {}", clone.url, dir); } Command::Commit(commit) => { println!("Committing: {}", commit.message); if let Some(author) = commit.author { println!("Author: {}", author); } } } } ``` -------------------------------- ### Enabling Serde Support for Command Metadata Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md Shows how to enable Serde support for the argh crate to serialize command metadata into formats like JSON. ```toml [dependencies] argh = { version = "0.1", features = ["serde"] } ``` -------------------------------- ### Flag Trait Example (Boolean) Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Demonstrates the `Flag` trait implementation for boolean types, where a switch toggles the value from false to true. ```Rust use argh::FromArgs; #[derive(FromArgs)] struct Args { /// Enable a feature #[argh(switch)] enable_feature: bool, } // If --enable-feature is present, args.enable_feature will be true. // Otherwise, it will be false. ``` -------------------------------- ### Usage Pattern with EarlyExit Source: https://github.com/google/argh/blob/master/_autodocs/02-from-args-trait.md Illustrates how to handle the `EarlyExit` result from `from_args`. It matches on the status to print help text or error messages and exits with the appropriate status code. ```rust match MyApp::from_args(&["app"], &args) { Ok(config) => process(config), Err(early_exit) => { match early_exit.status { Ok(()) => println!("{}", early_exit.output), // Help Err(()) => eprintln!("{}", early_exit.output), // Error } std::process::exit(match early_exit.status { Ok(()) => 0, Err(()) => 1, }); } } ``` -------------------------------- ### Usage of Integer Flag for Verbosity Source: https://github.com/google/argh/blob/master/_autodocs/05-flag-trait.md Example of using an integer type (u32) as a flag to control verbosity. The value increments with each occurrence of the flag. ```rust use argh::FromArgs; #[derive(FromArgs)] struct Args { /// verbosity level (0, 1, 2, etc.) #[argh(switch, short = 'v')] verbosity: u32, } // ./app → verbosity = 0 // ./app -v → verbosity = 1 // ./app -v -v -v → verbosity = 3 // ./app -vvvv → verbosity = 4 ``` -------------------------------- ### Parsing from Environment Source: https://github.com/google/argh/blob/master/_autodocs/02-from-args-trait.md Demonstrates parsing configuration directly from environment variables using `argh::from_env`. This method automatically handles errors by exiting the program. ```rust use argh::FromArgs; #[derive(FromArgs)] struct Config { #[argh(option)] count: usize, } let config: Config = argh::from_env(); // Exits on error ``` -------------------------------- ### Implementing Dynamic Subcommand Help Source: https://github.com/google/argh/blob/master/_autodocs/06-dynamic-subcommands.md Implement the try_from_args method for DynamicSubCommand to handle custom help messages for dynamic subcommands. This allows providing specific usage information when --help is requested. ```rust impl DynamicSubCommand for PluginCommand { fn try_from_args( command_name: &[&str], args: &[&str], ) -> Option> { let plugin_name = command_name.last()?; // ... check if known ... // Could provide help here if args.contains(&"--help") || args.contains(&"help") { return Some(Err(EarlyExit { output: format!( "Usage: {} {} \nThis is the {} plugin\n", command_name[0], plugin_name, plugin_name ), status: Ok(()), })); } Some(Ok(PluginCommand { name: plugin_name.to_string(), args: args.to_vec(), })) } } ``` -------------------------------- ### Enum Parsing Examples Source: https://github.com/google/argh/blob/master/_autodocs/04-from-arg-value.md Illustrates successful parsing of valid enum variants and the error message for invalid input when using the derive(FromArgValue) macro. ```rust // These all parse successfully: Color::from_arg_value("red") // → Ok(Color::Red) Color::from_arg_value("green") // → Ok(Color::Green) Color::from_arg_value("blue") // → Ok(Color::Blue) // This fails with helpful message: Color::from_arg_value("yellow") // → Err("expected \"red\" or \"green\" or \"blue\"") ``` -------------------------------- ### Example Usage of Blanket FromArgValue Source: https://github.com/google/argh/blob/master/_autodocs/04-from-arg-value.md Demonstrates using types that automatically implement FromArgValue via FromStr, such as IpAddr and u16, within a FromArgs struct. ```rust use argh::FromArgs; use std::net::IpAddr; #[derive(FromArgs)] struct ServerConfig { /// server binding address #[argh(option)] bind: IpAddr, // Automatically uses FromStr impl /// port number #[argh(option)] port: u16, // Built-in FromStr impl } ``` -------------------------------- ### Generate Help Information Source: https://github.com/google/argh/blob/master/_autodocs/08-shared-types.md Use this function to display help messages for command-line arguments. It requires the type to implement the `ArgsInfo` trait. ```rust use argh::ArgsInfo; fn show_help() { let info = T::get_args_info(); println!("Usage: {}", info.name); println!("\n{}\"n", info.description); if !info.flags.is_empty() { println!("Options:"); for flag in info.flags { println!(" {:?}", flag); } } } ``` -------------------------------- ### commands Method Source: https://github.com/google/argh/blob/master/_autodocs/06-dynamic-subcommands.md Provides metadata about all dynamically available subcommands, including their name, alias, and description. ```APIDOC ### `commands` ```rust fn commands() -> &'static [&'static CommandInfo] ``` **Purpose**: Provide metadata about all dynamically available subcommands. **Parameters**: None **Returns**: `&'static [&'static CommandInfo]` — Slice of command metadata **Details**: - Must return a static slice (lifetime `'static`) - Each `CommandInfo` contains: `name`, `short` (alias char), `description` - Can use `Box::leak()` to convert heap-allocated data to static references - Called by help system to list available commands ``` -------------------------------- ### CLI with Subcommands Source: https://github.com/google/argh/blob/master/_autodocs/INDEX.md Illustrates how to structure a CLI application with subcommands using Argh. This pattern is suitable for applications that perform different actions based on a subcommand. ```rust #[derive(FromArgs)] struct App { #[argh(subcommand)] cmd: Commands, } #[derive(FromArgs)] #[argh(subcommand)] enum Commands { #[argh(subcommand, name = "build")] Build(BuildCmd), } ``` -------------------------------- ### Enum Usage in FromArgs Source: https://github.com/google/argh/blob/master/_autodocs/04-from-arg-value.md Shows how to use an enum with derive(FromArgValue) as an argument option within a FromArgs struct, including example commands and error output. ```rust use argh::{FromArgs, FromArgValue}; #[derive(FromArgValue)] enum LogLevel { Debug, Info, Warn, Error, } #[derive(FromArgs)] struct AppConfig { /// logging level #[argh(option)] log_level: LogLevel, } // Command: ./app --log-level debug // Result: AppConfig { log_level: LogLevel::Debug } // Command: ./app --log-level invalid // Error: Error parsing option '--log-level' with value 'invalid': // expected "debug" or "info" or "warn" or "error" ``` -------------------------------- ### Flag Trait Example (Integer) Source: https://github.com/google/argh/blob/master/_autodocs/MANIFEST.txt Shows the `Flag` trait implementation for integer types, allowing multiple occurrences to increment the value (e.g., for verbosity levels). ```Rust use argh::FromArgs; #[derive(FromArgs)] struct Args { /// Increase verbosity level #[argh(flag, short = 'v')] verbosity: u8, } // Example usage: // $ ./my_binary -v => args.verbosity = 1 // $ ./my_binary -vv => args.verbosity = 2 // $ ./my_binary -vvv => args.verbosity = 3 ```