structargs
structargs turns a Zig struct into a command-line interface.
Instead of building a parser through chained builder calls, you declare one options struct, and
structargs derives the flags, defaults, enums, subcommands, and help output from that type at
comptime.
Features
The CLI schema lives in one Zig struct:
- normal fields become options
- optional fields and default values become optional flags
__shorts__declares short aliases__messages__declares help text
- Nested subcommands are declared with
__commands__: union(enum) - Help and usage text are generated from the same type definition
--versionsupport is enabled throughversion_stringprint_help_on_errorcan print stderr help before returning parse errorsSupported option value types include:
- All primitive types, such as
i8,u16,f32,bool []const u8Enum
- All primitive types, such as
Usage
See structargs-demo.zig.
| |
The parse result keeps the structured values on opt.options and also carries:
opt.program_nameopt.positional_argumentsopt.raw_argumentsopt.printHelp(writer)
Parse options
structargs.parse(..., .{ ... }) accepts these metadata options:
argument_prompt: Appended to the top-level usage line, for example[file]or[--] paths...version_string: Printed when--versionis presentprint_help_and_exit: Whentrue,--helpand--versionprint and exit immediatelyprint_help_on_error: Whentrue, parse errors print help to stderr before the error is returned
For subcommands, print_help_on_error prints the help for the current subcommand context instead of
always falling back to the top-level command.
Acknowledgment
Blog post explaining how structargs is implemented: What I learn by implementing argparser in Zig.
When implementing structargs, I referred to the following projects to learn how to write
idiomatic Zig code. Many thanks!