### Build Example Binaries with Pixi Source: https://github.com/forfudan/argmojo/blob/main/README.md Use this command to build all example binaries provided by ArgMojo. ```bash pixi run build ``` -------------------------------- ### Install Fish Completions Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Instructions for installing Fish completions, which are automatically loaded from the `~/.config/fish/completions/` directory. ```shell # Fish auto-loads from this directory myapp --completions fish > ~/.config/fish/completions/myapp.fish ``` -------------------------------- ### Example Response File Format Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates the format of a response file, where each non-empty line is an argument and lines starting with '#' are ignored. Whitespace is trimmed from each line. ```text # args.txt — common flags for the build --verbose --output=build/release --jobs=4 # source files src/main.mojo src/utils.mojo ``` -------------------------------- ### mgit: Subcommand Dispatch Examples Source: https://github.com/forfudan/argmojo/blob/main/README.md Examples of dispatching various `mgit` subcommands, including cloning a repository, committing changes, viewing logs, and pushing to a remote. ```bash ./mgit clone https://example.com/repo.git my-project --depth 1 ``` ```bash ./mgit commit -am "initial commit" ``` ```bash ./mgit log --oneline -n 20 --author "Alice" ``` ```bash ./mgit -v push origin main --force --tags ``` -------------------------------- ### Install Bash Completions Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Instructions for installing Bash completions, either for a one-shot session using `eval` or persistently by sourcing a file added to `.bashrc`. ```shell # One-shot (current session only) eval "$(myapp --completions bash)" # Persistent myapp --completions bash > ~/.bash_completion.d/myapp # Then add to ~/.bashrc: source ~/.bash_completion.d/myapp ``` -------------------------------- ### Example Application Help Output Source: https://github.com/forfudan/argmojo/wiki/Home An example of the detailed help output generated by Argmojo, including usage instructions, arguments, and options. ```console A CJK-aware text search tool usage: myapp [path] [OPTIONS] arguments: pattern Search pattern path Search path options: -l, --ling Use Lingming IME for encoding -i, --ignore-case Case-insensitive search -v, --verbose Increase verbosity (-v, -vv, -vvv) -d, --max-depth N Maximum directory depth -f, --format {json,csv,table} Output format --color / --no-color Enable colored output -?, -h, --help Show this help message -V, --version Show version ``` -------------------------------- ### Example Multi-Value Option Usage Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates how multi-value options are parsed from the command line. ```shell myapp --point 10 20 # point = ["10", "20"] ``` ```shell myapp --rgb 255 128 0 # rgb = ["255", "128", "0"] ``` -------------------------------- ### Install Zsh Completions Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Instructions for installing Zsh completions by placing the generated script in your `fpath` and ensuring the completion directory is loaded. ```shell # Place in your fpath (file must be named _myapp) myapp --completions zsh > ~/.zsh/completions/_myapp # Make sure ~/.zsh/completions is in fpath (add to ~/.zshrc): # fpath=(~/.zsh/completions $fpath) # autoload -Uz compinit && compinit ``` -------------------------------- ### Convenience Prefix Matching Examples Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Illustrates how prefix matching provides convenience for long option names, reducing typing. Examples include '--max' for '--max-depth' and '--ig' for '--ignore-case'. ```shell myapp --max 5 # instead of --max-depth 5 myapp --ig # instead of --ignore-case ``` -------------------------------- ### Shell Example for Response Files Source: https://github.com/forfudan/argmojo/wiki/Home Shows how to use a response file on the command line, equivalent to passing arguments directly. ```shell mytool @args.txt # equivalent to: mytool --verbose --output=build/release --jobs=4 src/main.mojo src/utils.mojo ``` -------------------------------- ### Stop Marker Example: Passing Arguments Resembling Options Source: https://github.com/forfudan/argmojo/wiki/Home Shows how '--' allows passing arguments that look like options, such as strings starting with '-' or file paths, as positional arguments. ```shell myapp --ling -- "-v is not a flag here" ./src # ling = True (parsed before --) # pattern = "-v is not a flag here" # path = "./src" ``` -------------------------------- ### Example Key-Value Map Option Usage Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates parsing key-value pairs using `.map_option()`. Equals syntax is supported. ```shell myapp --define CC=gcc -D CXX=g++ # result.get_map("define") → {"CC": "gcc", "CXX": "g++"} ``` -------------------------------- ### Example Prompt Formats Source: https://github.com/forfudan/argmojo/wiki/Home Illustrates different prompt formats based on argument configuration, including help text, choices, and defaults. ```text [choice1/choice2/choice3] (default_value): _ ``` ```console Username: ← help text, no choices, no default Enter your API token: ← custom prompt text Server region [us/eu/ap] (us): ← help text + choices + default Enable verbose output [y/n]: ← flag prompt ``` -------------------------------- ### Swift Argument Parser Example Source: https://github.com/forfudan/argmojo/blob/main/docs/declarative_api_planning.md Illustrates the usage of Swift's property wrappers for defining command-line arguments and options. ```swift struct Greet: ParsableCommand { @Argument(help: "The person's name.") var name: String @Option(name: .shortAndLong, help: "Repeat count.") var count: Int = 1 @Flag(inversion: .prefixedNo, help: "Include greeting.") var includeGreeting = true mutating func run() throws { for _ in 0.. String: return "Clone a repository." @staticmethod def name() -> String: return "clone" def run(self) raises: print("Cloning:", self.url.value) struct MyGit(Parsable): var verbose: Flag[short="v", help="Verbose output", persistent=True] @staticmethod def name() -> String: return "mgit" @staticmethod def description() -> String: return "A mini git tool." @staticmethod def subcommands() raises -> List[Command]: var subs = List[Command]() subs.append(Clone.to_command()) return subs^ def main() raises: var (git_args, result) = MyGit.parse_full() if git_args.verbose: print("Verbose mode on") if result.subcommand == "clone": var sub = result.get_subcommand_result() Clone.from_parse_result(sub).run() ``` See [`examples/declarative/jomo.mojo`](../examples/declarative/jomo.mojo) for a more complete example that mixes declarative and builder subcommands, including nested subcommands. ``` -------------------------------- ### Shell Example for parse_known_arguments() Source: https://github.com/forfudan/argmojo/wiki/Home Demonstrates the output of `parse_known_arguments()` with a mix of known and unknown arguments. ```shell wrapper input.txt --verbose --color -x --threads=4 # verbose = True # file = "input.txt" # unknown = ["--color", "-x", "--threads=4"] ``` -------------------------------- ### Example Choices Validation for Multi-Value Option Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates valid and invalid choices for a multi-value option. ```shell myapp --route north east # ✓ both valid ``` ```shell myapp --route north up # ✗ 'up' is not a valid choice ``` -------------------------------- ### Example Key-Value Map Option with Delimiter Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates passing multiple key-value pairs as a single token using a specified delimiter. ```shell myapp --define CC=gcc,CXX=g++ # result.get_map("define") → {"CC": "gcc", "CXX": "g++"} ``` -------------------------------- ### Shell Examples for Exactly-One Pattern Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Shows command-line invocations demonstrating the behavior of the combined one-required and mutually exclusive group. ```shell myapp --json # OK myapp --yaml # OK myapp # Error: At least one of the following arguments is required: '--json', '--yaml' myapp --json --yaml # Error: Arguments are mutually exclusive: '--json', '--yaml' ``` -------------------------------- ### Prefix Matching Examples Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates how prefix matching resolves to long options. Unambiguous prefixes like '--verb' map to '--verbose', and '--out' maps to '--output'. ```shell myapp --verb # resolves to --verbose myapp --out file.txt # resolves to --output file.txt myapp --out=file.txt # resolves to --output=file.txt ``` -------------------------------- ### Example Choices Validation Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates valid and invalid values for an option with choices validation. ```shell myapp --log-level debug # OK ``` ```shell myapp --log-level trace # Error: Invalid value 'trace' for argument 'log-level' # (choose from 'debug', 'info', 'warn', 'error') ``` -------------------------------- ### Append Option Usage Examples Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates various ways to provide values for an append option and the resulting list. All value syntaxes work with append options. ```shell myapp --tag alpha --tag beta --tag gamma # tags = ["alpha", "beta", "gamma"] myapp -t alpha -t beta # tags = ["alpha", "beta"] myapp --tag=alpha --tag=beta # tags = ["alpha", "beta"] myapp -talpha -tbeta # tags = ["alpha", "beta"] myapp # tags = [] (empty list, not provided) ``` -------------------------------- ### Example Usage of Positional Arguments Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates how positional arguments are parsed from the command line, where order determines assignment to the defined arguments. ```shell myapp "hello" ./src # ↑ ↑ # pattern path ``` -------------------------------- ### Value Delimiter Option Usage Examples Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates how values are parsed when a delimiter is used, including accumulation across multiple option occurrences and handling of single values. ```shell myapp --env dev,staging,prod # envs = ["dev", "staging", "prod"] myapp --env=dev,staging # envs = ["dev", "staging"] myapp -e dev,prod # envs = ["dev", "prod"] myapp --env dev,staging --env prod # envs = ["dev", "staging", "prod"] (values accumulate across uses) myapp --env single # envs = ["single"] (no delimiter → one-element list) myapp # envs = [] (not provided → empty list) ``` -------------------------------- ### Shell Examples for Negative Expressions Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates various command-line invocations when `allow_negative_expressions()` is enabled, showing how different inputs are parsed as positional arguments or options. ```shell calc "-1/3*pi" -p 10 # expr = "-1/3*pi", precision = "10" ``` ```shell calc "-sin(2)" # expr = "-sin(2)" ``` ```shell calc -e # expr = "-e" (because -e is not a registered short option) ``` ```shell calc -p 10 hello # precision = "10", expr = "hello" (-p IS registered, so it's parsed as the -p short option taking 10 as its value) ``` -------------------------------- ### Shell Completion Usage Examples Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Users can generate shell completion scripts by running the application with the `--completions` flag followed by the desired shell (bash, zsh, or fish). ```sh myapp --completions bash # prints Bash completion script and exits ``` ```sh myapp --completions zsh # prints Zsh completion script and exits ``` ```sh myapp --completions fish # prints Fish completion script and exits ``` -------------------------------- ### Shell Examples for Multiple One-Required Groups Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Shows command-line invocations for a command with multiple independent one-required groups, highlighting successful and failed validation scenarios. ```shell myapp --json --input f.txt # OK (both groups satisfied) myapp --json # Error (source group unsatisfied) ``` -------------------------------- ### Customize Root Command Builder Source: https://github.com/forfudan/argmojo/blob/main/docs/declarative_api_planning.md Customize the root command's builder, for example, to set header colors or add tips, before parsing arguments. Use `to_command()` to get the command builder and `parse_full_from_command()` to parse arguments against the customized builder. ```mojo def main() raises: var command = MyGit.to_command() # tree already assembled via subcommands() command.header_color["CYAN"]() command.add_tip("Run 'mgit help ' for details") var (git_args, result) = MyGit.parse_full_from_command(command^) var sub = result.get_subcommand_result() if result.subcommand == "clone": Clone.from_parse_result(sub).run() elif result.subcommand == "push": Push.from_parse_result(sub).run() ``` -------------------------------- ### Define Login Command with Prompting Arguments in Mojo Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Sets up a 'login' command with user, token, and region arguments, all enabled for interactive prompting. ```mojo from argmojo import Argument, Command def main() raises: var command = Command("login", "Authenticate with the service") command.add_argument( Argument("user", help="Username") .long["user"]() .required() .prompt() ) command.add_argument( Argument("token", help="API token") .long["token"]() .required() .prompt["Enter your API token"]() ) command.add_argument( Argument("region", help="Server region") .long["region"]() .choice["us"]() .choice["eu"]() .choice["ap"]() .default["us"]() .prompt() ) var result = command.parse() ``` -------------------------------- ### Typical Subcommand Flow Source: https://github.com/forfudan/argmojo/blob/main/docs/declarative_api_planning.md Illustrates two common patterns for parsing commands and dispatching to subcommands. The first shows a simple flow using `parse_full()` and manual string-based dispatch. The second demonstrates customization using `to_command()` and `parse_full_from_command()`. ```mojo # Simple — tree built automatically via subcommands() hook var (git_args, result) = MyGit.parse_full() if result.subcommand == "clone": var sub = result.get_subcommand_result() Clone.from_parse_result(sub).run() # With customization — to_command() already includes subcommands var command = MyGit.to_command() command.header_color["CYAN"]() var (git_args, result) = MyGit.parse_full_from_command(command^) ``` -------------------------------- ### Retrieve Count Flag Value Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Get the integer count of a flag that was defined with .count(). ```mojo var level = result.get_count("verbose") # Int if level >= 2: print("Debug-level output enabled") ``` -------------------------------- ### Configure Pattern with Free Functions Source: https://github.com/forfudan/argmojo/blob/main/docs/declarative_api_planning.md Demonstrates the 'configure' pattern using free functions or inline modifications for non-capturing callbacks, as Mojo 0.26.2 supports this for argument configuration. ```mojo # No code example provided in the source for this specific pattern. ``` -------------------------------- ### Create a Command Object Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Instantiate a Command object to define your program's name, description, and version. Add arguments to this command before parsing. ```mojo var command = Command("myapp", "A short description of the program", version="1.0.0") # ... add arguments ... var result = command.parse() ``` -------------------------------- ### Add Package Repository to pixi.toml Source: https://github.com/forfudan/argmojo/blob/main/README.md Configure your pixi.toml to include the modular-community package repository for installing ArgMojo. ```toml channels = ["https://conda.modular.com/max", "https://repo.prefix.dev/modular-community", "conda-forge"] ``` -------------------------------- ### Shell Examples for One-Required Group Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Illustrates valid and invalid command-line invocations for a one-required argument group. ```shell myapp --json # OK (one provided) myapp --yaml # OK (one provided) myapp # Error: At least one of the following arguments is required: '--json', '--yaml' myapp --json --yaml # OK (at least one is satisfied — both is fine for one_required alone) ``` -------------------------------- ### Persistent Flag Placement Examples Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates that persistent flags work correctly regardless of their position relative to the subcommand. ```shell app --verbose search "fn main" # flag BEFORE subcommand app search --verbose "fn main" # flag AFTER subcommand (same result) app -v search -o json "fn main" # short forms work too ``` -------------------------------- ### Define CLI Application with Subcommands Source: https://github.com/forfudan/argmojo/blob/main/docs/argmojo_overall_planning.md Define the main application command, add arguments, and register subcommands like 'search' and 'init'. This structure allows for a hierarchical command-line interface. ```mojo var app = Command("app", "My CLI tool", version="0.3.0") app.add_argument(Argument("verbose", help="Verbose output").long["verbose"]().short["v"]().flag()) var search = Command("search", "Search for patterns") search.add_argument(Argument("pattern", help="Search pattern").required().positional()) search.add_argument(Argument("max-depth", help="Max depth").long["max-depth"]().short["d"]().takes_value()) var init = Command("init", "Initialize a new project") init.add_argument(Argument("name", help="Project name").required().positional()) app.add_subcommand(search) app.add_subcommand(init) var result = app.parse() if result.subcommand == "search": var sub = result.subcommand_result var pattern = sub.get_string("pattern") ``` -------------------------------- ### Example Usage of Required-Together Arguments Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates valid and invalid command-line invocations when using `required_together()` for 'username' and 'password'. ```shell myapp --username admin --password secret # OK — both provided myapp # OK — neither provided myapp --username admin # Error: Arguments required together: # '--password' required when '--username' is provided myapp --password secret # Error: Arguments required together: # '--username' required when '--password' is provided ``` -------------------------------- ### Display Help and Version for mgrep Source: https://github.com/forfudan/argmojo/blob/main/README.md Shows how to display the help message and version information for the mgrep CLI. ```bash ./mgrep --help ``` ```bash ./mgrep --version ``` -------------------------------- ### Development: Build Package Source: https://github.com/forfudan/argmojo/blob/main/README.md Command to build the project package using `pixi`. ```bash pixi run package ``` -------------------------------- ### Help Output for Key-Value Map Options Source: https://github.com/forfudan/argmojo/wiki/Home Shows the placeholder format for map options in the help message, indicating the expected `` format. ```console -D, --define ... Define a variable ``` -------------------------------- ### Hybrid ArgMojo API Example Source: https://github.com/forfudan/argmojo/blob/main/README.md Combine the Builder and Declarative APIs by converting a struct to a `Command` object. This allows for advanced features like mutually exclusive groups and implications while retaining type safety. ```mojo var command = Deploy.to_command() # struct → Command command.mutually_exclusive(["force", "dry_run"]) command.implies("force", "validated") var deploy = Deploy.parse_from_command(command^) # Command → typed struct ``` -------------------------------- ### mgit: Root Help Command Source: https://github.com/forfudan/argmojo/blob/main/README.md Display the root help message for `mgit`, which includes available commands and global options. ```bash ./mgit --help ``` -------------------------------- ### Non-Interactive Use Example Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates non-interactive use where input is piped. Prompts are still printed to stdout, but input is read from the pipe. ```shell echo "" | ./login --user alice --token secret ``` -------------------------------- ### Ambiguous Prefix Error Example Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Illustrates the error message when an ambiguous prefix is used. The parser lists all possible matching options. ```shell myapp --ver # Error: Ambiguous option '--ver' could match: '--verbose', '--version-info' ``` -------------------------------- ### Example Error Message for Conditional Requirement Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Displays the typical error message generated by Argmojo when a conditional argument requirement is not met. ```console Error: Argument '--output' is required when '--save' is provided ``` -------------------------------- ### Help Subcommand Usage Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Illustrates the automatic registration and usage of the 'help' subcommand, which mirrors standard CLI behavior like 'git help'. ```shell app help search # equivalent to: app search --help app help init # equivalent to: app init --help app help # shows root help (same as: app --help) ``` -------------------------------- ### Argmojo Command-Line Syntax Examples Source: https://github.com/forfudan/argmojo/blob/main/docs/argmojo_overall_planning.md Illustrates various ways to invoke commands with Argmojo, including long and short options, merged flags, attached values, and special argument handling like negation and remainder parsing. ```bash # Long options --flag # Boolean flag --key value # Key-value (space separated) --key=value # Key-value (equals separated) --key=value # Require-equals syntax (when .require_equals()) --key # Default-if-no-value (when .default_if_no_value()) --no-flag # Negation (when .negatable()) --verb # Prefix match → --verbose (if unambiguous) # Short options -f # Boolean flag -k value # Key-value -abc # Merged short flags → -a -b -c -ofile.txt # Attached short value → -o file.txt -abofile.txt # Mixed: -a -b -o file.txt -vvv # Count flag → verbose = 3 # Positional arguments pattern # By order of add_argument() calls # Special -- # Stop parsing options; rest becomes positional --help / -h / -? # Show auto-generated help --version / -V # Show version @args.txt # Response file expansion (when enabled) cmd rest... # Remainder positional (consume all remaining tokens) # Subcommands app search pattern # Dispatch to subcommand app help search # Show subcommand help app --verbose search # Persistent flags before subcommand ``` -------------------------------- ### Shell Examples for Mutually Exclusive Arguments Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates valid and invalid command-line invocations when using mutually exclusive argument groups. ```shell myapp --input data.csv # OK myapp --stdin # OK myapp --input data.csv --stdin # Error: mutually exclusive ``` -------------------------------- ### Development: Run Tests Source: https://github.com/forfudan/argmojo/blob/main/README.md Command to execute the project's test suite using `pixi`. ```bash pixi run test ``` -------------------------------- ### Argument and Command Definition Source: https://github.com/forfudan/argmojo/blob/main/docs/declarative_api_planning.md Shows the basic syntax for defining arguments with long and short flags, and creating a command object to parse them. This represents the unchanged core functionality. ```txt Argument(...).long["x"]().short["y"]().flag() Command("app").add_argument(...).parse() → ParseResult ``` -------------------------------- ### Remainder Positional Argument Example Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates how a remainder positional argument captures all remaining tokens, including options and flags, as a list of strings. ```shell runner myapp --verbose -x --output=foo.txt # program = "myapp" # args = ["--verbose", "-x", "--output=foo.txt"] ``` -------------------------------- ### Shell Examples for One-Required with Value-Taking Options Source: https://github.com/forfudan/argmojo/blob/main/docs/user_manual.md Demonstrates valid and invalid command-line usage when a one-required group contains both value-taking arguments and flags. ```shell myapp --input data.txt # OK myapp --stdin # OK myapp # Error: At least one of the following arguments is required: '--input', '--stdin' ``` -------------------------------- ### Stop Marker Example: Parsing '--ling' Source: https://github.com/forfudan/argmojo/wiki/Home Demonstrates how '--' prevents '--ling' from being parsed as an option, treating it instead as a positional argument. ```shell myapp -- --ling # ling = False (the -- stopped option parsing) # pattern = "--ling" (treated as a positional value) ``` -------------------------------- ### Example of Multi-Value Choices Validation Failure Source: https://github.com/forfudan/argmojo/wiki/Home Shows a command-line invocation that fails validation because one of the provided values for a multi-value option is not in the allowed choices. ```shell myapp --route north up # ✗ 'up' is not a valid choice ```