Parser API Reference
The ArgumentParser is the main interface for defining and parsing command-line arguments.
Creating a Parser
ArgumentParser.init
pub fn init(allocator: std.mem.Allocator, options: InitOptions) !ArgumentParserCreates a new argument parser.
Parameters:
allocator- Memory allocator for internal data structuresoptions- Initialization options
InitOptions:
pub const InitOptions = struct {
name: []const u8, // Program name (required)
version: ?[]const u8 = null, // Version string
description: ?[]const u8 = null, // Program description
epilog: ?[]const u8 = null, // Text after help
add_help: bool = true, // Add --help flag
add_version: bool = true, // Add --version flag
config: ?Config = null, // Parser configuration
};Example:
var parser = try args.ArgumentParser.init(allocator, .{
.name = "myapp",
.version = "1.0.0",
.description = "My application",
});
defer parser.deinit();ArgumentParser.deinit
pub fn deinit(self: *ArgumentParser) voidReleases all resources used by the parser.
Parsing Behavior Notes
- Long boolean options support
--no-<name>whenConfig.allow_negated_flags = true(default). - Inline values are rejected for flag-style actions (
store_true,store_false,count,help,version). - When
Config.case_sensitive = false, long option names andchoices/expectchecks are ASCII case-insensitive. - In
strictmode, unknown long options and unknown subcommands can emit closest-match suggestions whenConfig.suggest_closest = true. - Built-in names
--helpand--versionare included in unknown-option suggestion candidates whenConfig.suggest_builtin_commands = true. - Unknown subcommand suggestions are controlled by
Config.suggest_subcommands. - Help generation respects
Config.program_name,Config.help_indent, andConfig.help_line_width.
Adding Arguments
addFlag
pub fn addFlag(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
dest: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
}) !voidAdds a boolean flag (e.g., --verbose, -v).
Example:
try parser.addFlag("verbose", .{
.short = 'v',
.help = "Enable verbose output",
});addOption
pub fn addOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
value_type: ValueType = .string,
default: ?[]const u8 = null,
required: bool = false,
choices: []const []const u8 = &.{},
metavar: ?[]const u8 = null,
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
validator: ?validation.ValidatorFn = null,
expect: []const []const u8 = &.{},
suggestion_hint: ?[]const u8 = null,
custom_error_message: ?[]const u8 = null,
decode_mode: DecodeMode = .none,
}) !voidAdds an option that takes a value.
Example:
try parser.addOption("output", .{
.short = 'o',
.help = "Output file",
.default = "output.txt",
});addPositional
pub fn addPositional(self: *ArgumentParser, name: []const u8, options: struct {
help: ?[]const u8 = null,
value_type: ValueType = .string,
required: bool = true,
default: ?[]const u8 = null,
nargs: Nargs = .{ .exact = 1 },
metavar: ?[]const u8 = null,
choices: []const []const u8 = &.{},
expect: []const []const u8 = &.{},
validator: ?validation.ValidatorFn = null,
hidden: bool = false,
decode_mode: DecodeMode = .none,
}) !voidAdds a positional argument.
Example:
try parser.addPositional("input", .{
.help = "Input file",
.required = true,
});addDecryptionOption
pub fn addDecryptionOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
metavar: ?[]const u8 = "BASE64",
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
validator: ?validation.ValidatorFn = null,
expect: []const []const u8 = &.{},
suggestion_hint: ?[]const u8 = null,
custom_error_message: ?[]const u8 = null,
url_safe: bool = false,
}) !voidAdds a string option that decodes incoming Base64 input before validation and storage.
addIntOption
pub fn addIntOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
metavar: ?[]const u8 = "INT",
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
expect: []const []const u8 = &.{},
min: ?i64 = null,
max: ?i64 = null,
}) !voidAdds an integer-typed option (.int value type) with optional range validation.
addFloatOption
pub fn addFloatOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
metavar: ?[]const u8 = "FLOAT",
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
expect: []const []const u8 = &.{},
min: ?f64 = null,
max: ?f64 = null,
}) !voidAdds a float-typed option (.float value type) with optional range validation.
addUintOption
pub fn addUintOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
metavar: ?[]const u8 = "UINT",
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
expect: []const []const u8 = &.{},
min: ?u64 = null,
max: ?u64 = null,
}) !voidAdds an unsigned integer-typed option (non-negative .uint value type) with optional range validation.
addHexOption
pub fn addHexOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
metavar: ?[]const u8 = "HEX",
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
validator: ?validation.ValidatorFn = null,
expect: []const []const u8 = &.{},
suggestion_hint: ?[]const u8 = null,
custom_error_message: ?[]const u8 = null,
}) !voidAdds an option whose value is decoded from hexadecimal before storage.
addFalseFlag
pub fn addFalseFlag(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
dest: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
}) !voidAdds an inverse boolean flag that stores false when present.
Example:
try parser.addFalseFlag("color", .{ .help = "Disable color output" });addAllFlag
pub fn addAllFlag(self: *ArgumentParser, options: struct {
name: []const u8 = "all",
short: ?u8 = null,
help: ?[]const u8 = "Select all items",
dest: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
}) !voidaddSelectOption
pub fn addSelectOption(self: *ArgumentParser, options: struct {
name: []const u8 = "select",
short: ?u8 = null,
help: ?[]const u8 = "Select specific items",
value_type: ValueType = .string,
default: ?[]const u8 = null,
required: bool = false,
choices: []const []const u8 = &.{},
metavar: ?[]const u8 = null,
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
validator: ?validation.ValidatorFn = null,
expect: []const []const u8 = &.{},
}) !voidaddSelectOrAll
Adds an exclusive helper pair around --select and --all.
addSelectCsvOption
Adds a CSV-oriented --select option for multi-target workflows.
addSelectOrAllCsv
Adds an exclusive helper pair around --select <csv-list> and --all.
addIncludeOption
Adds a conventional --include option for comma-separated filters.
addExcludeOption
Adds a conventional --exclude option for comma-separated filters.
addIncludeExclude
Adds both include/exclude options under one group for help organization.
addPathOption
Adds a path option (ValueType.path) for generic path workflows.
addFileOption
Adds a file path option with optional existence validation.
addDirectoryOption
Adds a directory path option with optional existence validation.
addFileOptionWithExtensions
pub fn addFileOptionWithExtensions(
self: *ArgumentParser,
name: []const u8,
comptime allowed_extensions: []const []const u8,
options: struct { ... },
) !voidAdds a file path option with reusable extension validation and optional existence checks.
addFileNameOption
Adds a file-name-only option (safe name, no path separators) with optional custom validator.
addFileNameOptionWithExtensions
pub fn addFileNameOptionWithExtensions(
self: *ArgumentParser,
name: []const u8,
comptime allowed_extensions: []const []const u8,
options: struct { ... },
) !voidaddEndpointOption
Adds a validated endpoint option in host:port format.
Example:
try parser.addEndpointOption("service", .{
.help = "Service endpoint (host:port)",
});Numeric Typed Option Helpers
Convenience helpers for typed numeric options:
addIntOption—.intvalue type, optionalmin/maxrange validationaddFloatOption—.floatvalue type, optionalmin/maxrange validationaddUintOption—.uintvalue type (non-negative integers)
Example:
try parser.addIntOption("retries", .{
.short = 'r',
.help = "Retry count (0-10)",
.min = 0,
.max = 10,
.default = "3",
});
try parser.addFloatOption("threshold", .{
.short = 't',
.help = "Confidence threshold (0.0 to 1.0)",
.min = 0.0,
.max = 1.0,
.default = "0.75",
});
try parser.addUintOption("threads", .{
.short = 'p',
.help = "Worker thread count",
.default = "4",
});Decode / Encoding Option Helpers
addHexOption— Decodes hexadecimal input before storage
Example:
try parser.addHexOption("key", .{
.short = 'k',
.help = "Hex-encoded key material",
.required = true,
});Typed Input Helper Methods
The parser includes one-call helpers for common input formats:
addEmailOptionaddUrlOptionaddIpv4OptionaddIpOptionaddIpv6OptionaddHostNameOptionaddPortOptionaddEndpointOptionaddKeyValueOptionaddUuidOptionaddIsoDateOptionaddIsoDateTimeOptionaddYearOptionaddTimeOptionaddUnixTimestampOptionaddDateFlexibleOptionaddJsonOptionaddAbsolutePathOption
Each helper adds a .string option with an appropriate built-in validator.
Common helper option fields:
short,help,default,requiredmetavar,dest,env_varhidden,aliases,deprecatedvalidator(override default built-in validator)expect
Example:
try parser.addEmailOption("email", .{
.short = 'e',
.required = true,
.env_var = "APP_EMAIL",
});
try parser.addEndpointOption("service", .{
.help = "Service endpoint in host:port format",
.default = "localhost:8080",
});
try parser.addIpv6Option("host-v6", .{
.help = "Service IPv6 address",
});
try parser.addIpOption("host-any", .{
.help = "Service IP address (IPv4 or IPv6)",
});
try parser.addKeyValueOption("label", .{
.help = "Metadata label as key=value",
});
try parser.addOption("retries", .{
.value_type = .int,
.validator = args.Validators.intRange(1, 10),
.default = "3",
});
var result = try parser.parseProcess(init);
defer result.deinit();
const email = result.getString("email") orelse "";
const service = result.getString("service") orelse "localhost:8080";
const retries = result.getInt("retries") orelse 3;
const label = result.getKeyValue("label");Validator Aliases (Top-Level)
args.zig re-exports validation helpers for concise client-side usage:
pub const ValidatorFn = validation.ValidatorFn;
pub const Validators = validation.Validators;This allows direct usage like:
const validator = args.Validators.filePolicy(&[_][]const u8{"json"}, false, 3, 64);PromptSelectOrAllOptions
pub const PromptSelectOrAllOptions = struct {
select_key: []const u8 = "select",
all_key: []const u8 = "all",
question: []const u8 = "Choose target",
choices: []const []const u8,
default_choice: ?[]const u8 = null,
allow_all: bool = true,
case_sensitive: ?bool = null,
allow_prefix_match: bool = true,
suggest_closest: bool = true,
max_suggestion_distance: usize = 3,
max_attempts: usize = 3,
};SelectOrAllStrictOptions
Configuration for strict CSV select/all resolution with optional normalization and deduplication.
resolveSelectOrAllStrict
Resolves parsed --select and --all values into a canonical selection result:
var resolved = try args.resolveSelectOrAllStrict(allocator, &parsed, .{
.choices = &[_][]const u8{ "users", "groups", "logs" },
.allow_prefix_match = true,
.dedupe = true,
});
defer resolved.deinit();PromptSelectOrAllDecision
pub const PromptSelectOrAllDecision = union(enum) {
all: void,
selected: []const u8,
};resolveSelectOrAllWithPrompt
pub fn resolveSelectOrAllWithPrompt(
parsed: *const ParseResult,
options: PromptSelectOrAllOptions,
io: std.Io,
) !PromptSelectOrAllDecisionUses parsed --select / --all first. If missing, prompts the user interactively and validates the answer. The io parameter provides the I/O context (pass init.io from your main function).
resolveSelectOrAllWithPromptIO
pub fn resolveSelectOrAllWithPromptIO(
parsed: *const ParseResult,
options: PromptSelectOrAllOptions,
reader: *std.Io.Reader,
writer: *std.Io.Writer,
) !PromptSelectOrAllDecisionSame behavior as resolveSelectOrAllWithPrompt, but with explicit reader/writer references for tests and embedded runtimes.
parseCsvList
pub fn parseCsvList(allocator: std.mem.Allocator, raw: []const u8) ![][]const u8Parses comma-separated values into trimmed non-empty items.
deinitCsvList
pub fn deinitCsvList(allocator: std.mem.Allocator, items: [][]const u8) voidFrees memory returned by parseCsvList.
IncludeExcludeResolved
pub const IncludeExcludeResolved = struct {
include: [][]const u8,
exclude: [][]const u8,
allocator: std.mem.Allocator,
pub fn deinit(self: *IncludeExcludeResolved) void
};IncludeExcludeStrictOptions
pub const IncludeExcludeStrictOptions = struct {
include_key: []const u8 = "include",
exclude_key: []const u8 = "exclude",
choices: []const []const u8 = &.{},
all_keyword: ?[]const u8 = "all",
case_sensitive: bool = false,
allow_prefix_match: bool = true,
dedupe: bool = true,
fail_on_conflicts: bool = true,
};IncludeExcludeStrictResolved
pub const IncludeExcludeStrictResolved = struct {
all: bool,
include: [][]const u8,
exclude: [][]const u8,
allocator: std.mem.Allocator,
pub fn deinit(self: *IncludeExcludeStrictResolved) void
};resolveIncludeExclude
pub fn resolveIncludeExclude(
allocator: std.mem.Allocator,
parsed: *const ParseResult,
include_key: []const u8,
exclude_key: []const u8,
) !IncludeExcludeResolvedParses include/exclude CSV strings from parse results into reusable lists.
resolveIncludeExcludeStrict
pub fn resolveIncludeExcludeStrict(
allocator: std.mem.Allocator,
parsed: *const ParseResult,
options: IncludeExcludeStrictOptions,
) !IncludeExcludeStrictResolvedStrict resolver for filter workflows with optional choice canonicalization, deduplication, all keyword handling, and conflict detection.
addCounter
pub fn addCounter(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
dest: ?[]const u8 = null,
}) !voidAdds a counter argument (increments each time it's used).
Example:
try parser.addCounter("verbose", .{
.short = 'v',
.help = "Increase verbosity",
});addListOption
pub fn addListOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
metavar: ?[]const u8 = "LIST",
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
validator: ?validation.ValidatorFn = null,
expect: []const []const u8 = &.{},
suggestion_hint: ?[]const u8 = null,
custom_error_message: ?[]const u8 = null,
separator: u8 = ',',
}) !voidAdds a list/array option that splits a comma-separated value into an array of strings. Stored as .array type.
Example:
try parser.addListOption("allow-hosts", .{
.short = 'a',
.help = "Comma-separated list of allowed hosts",
});
// --allow-hosts a,b,c → result.getArray("allow-hosts") returns &[_][]const u8{"a", "b", "c"}addSecretOption
pub fn addSecretOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
metavar: ?[]const u8 = null,
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
}) !voidAdds a password/secret option stored as a string. The option is hidden from help output. The invoking application is responsible for disabling terminal echo when prompting.
addEnvOption
pub fn addEnvOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
value_type: ValueType = .string,
default: ?[]const u8 = null,
required: bool = false,
metavar: ?[]const u8 = null,
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
validator: ?validation.ValidatorFn = null,
expect: []const []const u8 = &.{},
}) !voidAdds an option with automatic environment variable fallback. The env var name is derived from the option name (uppercased, hyphens → underscores) unless env_var is explicitly provided.
Convenience wrapper around addOption with automatic env_var derivation.
Example:
// Env var derived as "DB_HOST" from "db-host"
try parser.addEnvOption("db-host", .{
.help = "Database hostname",
.default = "localhost",
});addLogLevel
pub fn addLogLevel(self: *ArgumentParser, verbose_options: struct {
name: []const u8 = "verbose",
short: ?u8 = 'v',
help: ?[]const u8 = "Increase verbosity level",
dest: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
}, quiet_options: struct {
name: []const u8 = "quiet",
short: ?u8 = 'q',
help: ?[]const u8 = "Decrease verbosity level (suppress output)",
dest: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
}) !voidAdds a --verbose / --quiet pair wired to a shared counter destination. --verbose increments, --quiet decrements the same counter.
Example:
try parser.addLogLevel(
.{ .name = "verbose", .short = 'v', .dest = "verbosity" },
.{ .name = "quiet", .short = 'q', .dest = "verbosity" },
);addSubcommand
pub fn addSubcommand(self: *ArgumentParser, spec: SubcommandSpec) !voidAdds a subcommand with its own arguments.
Example:
try parser.addSubcommand(.{
.name = "init",
.help = "Initialize project",
.args = &[_]args.ArgSpec{
.{ .name = "name", .positional = true, .required = true },
},
});addArg
pub fn addArg(self: *ArgumentParser, spec: ArgSpec) !voidAdds an argument with full specification.
addRequired
pub fn addRequired(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
value_type: ValueType = .string,
metavar: ?[]const u8 = null,
}) !voidShorthand for adding a required option.
Example:
try parser.addRequired("config", .{
.short = 'c',
.help = "Configuration file (required)",
});addHiddenFlag
pub fn addHiddenFlag(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
dest: ?[]const u8 = null,
}) !voidAdds a hidden flag that won't appear in help text.
addDeprecated
pub fn addDeprecated(self: *ArgumentParser, name: []const u8, warning: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
value_type: ValueType = .string,
}) !voidAdds a deprecated option with a warning message.
Example:
try parser.addDeprecated("old-format", "Use --format instead", .{});fromEnvOrDefault
pub fn fromEnvOrDefault(
self: *ArgumentParser,
name: []const u8,
env_var: []const u8,
default_value: []const u8,
options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
value_type: ValueType = .string,
},
) !voidAdds an option with environment variable fallback and programmatic default.
Example:
try parser.fromEnvOrDefault("token", "API_TOKEN", "default-token", .{
.help = "API authentication token",
});addAppend
pub fn addAppend(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
metavar: ?[]const u8 = null,
dest: ?[]const u8 = null,
}) !voidAdds an option that appends values to an array. Each occurrence of the option adds a new value to the array. Retrievable via result.getArray("name").
Example:
try parser.addAppend("include", .{
.short = 'I',
.help = "Include path (can be repeated)",
});
var result = try parser.parseProcess(init);
if (result.getArray("include")) |paths| {
for (paths) |p| std.debug.print("{s}\n", .{p});
}addMultiple
pub fn addMultiple(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
min: usize = 1,
max: ?usize = null,
metavar: ?[]const u8 = null,
}) !voidAdds an option that accepts multiple values (e.g. --numbers 1 2 3).
Example:
try parser.addMultiple("numbers", .{
.short = 'n',
.min = 1,
.max = 3,
});addBracketedListOption
pub fn addBracketedListOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
metavar: ?[]const u8 = null,
dest: ?[]const u8 = null,
}) !voidAdds an option that parses bracket-delimited inline lists — {a,b,c}, [a,b,c], <a,b,c>. Bracket detection is automatic and controlled by the allow_brackets config setting.
Example:
try parser.addBracketedListOption("tags", .{ .short = 't' });
// Usage: --tags {rust,zig,go} or --tags [a,b,c] or --tags <x,y,z>addFormatOption
pub fn addFormatOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
metavar: ?[]const u8 = "LIST",
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
formats: []const []const u8 = &.{},
}) !voidAdds an option that accepts a file format name. Pass an explicit array of allowed format names via formats.
Example:
try parser.addFormatOption("input-format", .{ .short = 'f', .default = "json" });addExtensionOption
pub fn addExtensionOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
metavar: ?[]const u8 = ".EXT",
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
extensions: []const []const u8 = &.{},
}) !voidAdds an option that accepts a file extension (e.g. .json, .yaml, .csv). Pass an explicit array of allowed extensions via extensions.
Example:
try parser.addExtensionOption("output-ext", .{ .short = 'o', .default = ".json" });addDurationOption
pub fn addDurationOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
}) !voidAdds an option that accepts and validates duration strings (e.g. 1h30m, 45s, 2d). Stored value is parsed into total seconds (u64).
Example:
try parser.addDurationOption("timeout", .{
.short = 't',
.default = "30s",
});addSizeOption
pub fn addSizeOption(self: *ArgumentParser, name: []const u8, options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
}) !voidAdds an option that accepts and validates byte-size strings (e.g. 512MB, 1GB, 4096). Stored value is parsed into total bytes (u64).
Example:
try parser.addSizeOption("buffer", .{
.short = 'b',
.default = "64MB",
});addRangeOption
pub fn addRangeOption(self: *ArgumentParser, name: []const u8, comptime T: type, comptime options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
min: ?T = null,
max: ?T = null,
}) !voidAdds a range-validated option supporting both integer and floating-point types.
Example:
try parser.addRangeOption("concurrency", i64, comptime .{
.short = 'c',
.min = 1,
.max = 8,
.default = "2",
});addCharRangeOption
pub fn addCharRangeOption(self: *ArgumentParser, name: []const u8, comptime options: struct {
short: ?u8 = null,
help: ?[]const u8 = null,
default: ?[]const u8 = null,
required: bool = false,
dest: ?[]const u8 = null,
env_var: ?[]const u8 = null,
hidden: bool = false,
aliases: []const []const u8 = &.{},
deprecated: ?[]const u8 = null,
min: ?usize = null,
max: ?usize = null,
}) !voidAdds an option validated by character length range (minimum and maximum character count).
Example:
try parser.addCharRangeOption("username", .{
.short = 'u',
.min = 3,
.max = 12,
});setGroup
pub fn setGroup(self: *ArgumentParser, group_name: []const u8) voidSets the argument group for subsequent arguments (used for help organization).
Example:
parser.setGroup("Advanced Options");
try parser.addFlag("verbose", .{});Utility Methods
hasArg
pub fn hasArg(self: *ArgumentParser, name: []const u8) boolChecks if an argument with the given name exists.
argCount
pub fn argCount(self: *ArgumentParser) usizeReturns the number of defined arguments.
subcommandCount
pub fn subcommandCount(self: *ArgumentParser) usizeReturns the number of defined subcommands.
printVersion
pub fn printVersion(self: *ArgumentParser) voidPrints the program version to stdout.
Parsing
parse
pub fn parse(self: *ArgumentParser, args_slice: []const []const u8) !ParseResultParses the provided argument slice.
Example:
const argv = [_][]const u8{ "-v", "--output", "file.txt" };
var result = try parser.parse(&argv);
defer result.deinit();parseProcess
pub fn parseProcess(self: *ArgumentParser, proc_init: std.process.Init) !ParseResultParses arguments from the current process using the process initialization context.
Example:
var result = try parser.parseProcess(init);
defer result.deinit();parseOr
pub fn parseOr(
self: *ArgumentParser,
args_slice: []const []const u8,
on_error: ?*const fn (err: anyerror, parser: *ArgumentParser) void,
) ParseResultParses arguments from a slice, returning a default (empty) ParseResult on error rather than propagating the error. The optional on_error callback is invoked with the error details before the default result is returned.
Example:
// Silent fallback — returns empty result on error
var result = parser.parseOr(args, null);
defer result.deinit();
// With custom error handler
fn handleError(err: anyerror, parser: *ArgumentParser) void {
std.debug.print("Parse failed: {}\n", .{err});
}
var result = parser.parseOr(args, handleError);
defer result.deinit();parseProcessOr
pub fn parseProcessOr(
self: *ArgumentParser,
proc_init: std.process.Init,
on_error: ?*const fn (err: anyerror, parser: *ArgumentParser) void,
) ParseResultProcess-aware variant of parseOr. Parses from std.process.Init and returns a default ParseResult on error. The optional on_error callback is invoked with the error details.
Example:
var result = parser.parseProcessOr(init, null);
defer result.deinit();
// With error handler that prints help
fn onParseError(err: anyerror, parser: *ArgumentParser) void {
parser.printHelp() catch {};
std.debug.print("Error: {}\n", .{err});
}
var result = parser.parseProcessOr(init, onParseError);
defer result.deinit();parseInto (Module-level Function)
pub fn parseInto(
allocator: std.mem.Allocator,
comptime T: type,
options: ArgumentParser.InitOptions,
args_slice: ?[]const []const u8,
init: ?std.process.Init,
) !ParseIntoResult(T)Parses command-line arguments directly into a struct type. Derives argument specs from struct fields at compile-time.
Parameters:
allocator- Memory allocatorT- The struct type to parse intooptions- Parser initialization optionsargs_slice- Argument slice to parse, ornullto use process argsinit- Process initialization context (std.process.Init), required ifargs_sliceisnull
Example:
const Config = struct {
verbose: bool,
output: ?[]const u8,
count: i32,
};
var result = try args.parseInto(allocator, Config, .{
.name = "myapp",
}, null, init);
defer result.deinit();
std.debug.print("Count: {d}\n", .{result.options.count});parseProcessInto (Convenience Function)
pub fn parseProcessInto(
allocator: std.mem.Allocator,
comptime T: type,
options: ArgumentParser.InitOptions,
init: std.process.Init,
) !ParseIntoResult(T)Convenience wrapper — same as parseInto(allocator, T, options, null, init). Avoids the null parameter.
Example:
// These are equivalent:
var result = try args.parseProcessInto(allocator, Config, .{ .name = "myapp" }, init);
var result = try args.parseInto(allocator, Config, .{ .name = "myapp" }, null, init);Function Aliases
For convenience, the library provides several aliases:
| Alias | Original Function | Description |
|---|---|---|
derive | parseInto | Parse args directly into a struct |
deriveProcess | parseProcessInto | Shorthand for process args parsing |
configure | initConfig | Set global configuration |
version | getLibraryVersion | Get library version string |
Example:
// These are equivalent:
var parsed = try args.parseInto(allocator, Config, options, null, init);
var parsed = try args.derive(allocator, Config, options, null, init);
// These are equivalent:
var parsed = try args.parseProcessInto(allocator, Config, options, init);
var parsed = try args.deriveProcess(allocator, Config, options, init);
// These are equivalent:
args.initConfig(.{ .use_colors = false });
args.configure(.{ .use_colors = false });Convenience Functions
createParser
pub fn createParser(allocator: std.mem.Allocator, name: []const u8) !ArgumentParserCreates a parser with common defaults.
Example:
var parser = try args.createParser(allocator, "myapp");
defer parser.deinit();createMinimalParser
pub fn createMinimalParser(allocator: std.mem.Allocator, name: []const u8) !ArgumentParserCreates a minimal parser (no colors).
Example:
var parser = try args.createMinimalParser(allocator, "myapp");
defer parser.deinit();quickParse
pub fn quickParse(comptime T: type, options: ArgumentParser.InitOptions, init: std.process.Init) !ParseIntoResult(T)One-shot parse using the global allocator. Convenience for simple CLIs where you don't need to manage allocator lifetime.
Example:
const Config = struct { verbose: bool, output: ?[]const u8 };
var result = try args.quickParse(Config, .{ .name = "myapp" }, init);
defer result.deinit();resetConfig
pub fn resetConfig() voidResets global configuration back to default values. Useful in tests to avoid state leakage between test cases.
Example:
args.initConfig(.{ .use_colors = false });
defer args.resetConfig(); // Restore defaults after testgetLibraryVersion
pub fn getLibraryVersion() []const u8Returns the library version string. Also available via the version alias.
Example:
std.debug.print("args.zig version: {s}\n", .{args.getLibraryVersion()});
// or
std.debug.print("args.zig version: {s}\n", .{args.version()});deriveOptions
pub fn deriveOptions(comptime T: type) []const ArgSpecDerives argument specifications from a struct type at compile-time. Useful if you need the specs without parsing.
Example:
const Config = struct { verbose: bool, count: i32 };
const specs = args.deriveOptions(Config);
// specs is []const ArgSpec with 2 entriesHelp and Completion
getHelp
pub fn getHelp(self: *ArgumentParser) ![]const u8Generates help text as a string.
printHelp
pub fn printHelp(self: *ArgumentParser) !voidPrints help text to stdout.
getUsage
pub fn getUsage(self: *ArgumentParser) ![]const u8Generates a short usage string.
generateCompletion
pub fn generateCompletion(self: *ArgumentParser, shell: Shell) ![]const u8Generates shell completion script.
Example:
const script = try parser.generateCompletion(.bash);
defer allocator.free(script);getVersion
pub fn getVersion(self: *ArgumentParser) []const u8Returns the parser's version string.
ParseResult
The result of parsing arguments.
Fields
pub const ParseResult = struct {
values: std.StringHashMap(ParsedValue),
positionals: std.ArrayList([]const u8),
remaining: std.ArrayList([]const u8),
subcommand: ?[]const u8,
subcommand_args: ?*ParseResult,
allocator: std.mem.Allocator,
};Methods
get
pub fn get(self: *const ParseResult, name: []const u8) ?ParsedValueGets a raw parsed value.
getString
pub fn getString(self: *const ParseResult, name: []const u8) ?[]const u8Gets a string value.
getInt
pub fn getInt(self: *const ParseResult, name: []const u8) ?i64Gets an integer value.
getBool
pub fn getBool(self: *const ParseResult, name: []const u8) ?boolGets a boolean value.
getFloat
pub fn getFloat(self: *const ParseResult, name: []const u8) ?f64Gets a float value.
getUint
pub fn getUint(self: *const ParseResult, name: []const u8) ?u64Gets an unsigned integer value.
getArray
pub fn getArray(self: *const ParseResult, name: []const u8) ?[]const []const u8Gets an array value (returned by addListOption).
getEnum
pub fn getEnum(self: *const ParseResult, comptime T: type, name: []const u8) ?TGets an enum value by converting the stored string to the given enum type. Returns null if the value is missing or the string does not match any enum field.
Example:
const Level = enum { debug, info, warn, error };
const level = result.getEnum(Level, "log-level") orelse .info;getOrString
pub fn getOrString(self: *const ParseResult, name: []const u8, default: []const u8) []const u8Gets a string value with a default fallback.
getOrInt
pub fn getOrInt(self: *const ParseResult, name: []const u8, default: i64) i64Gets an integer value with a default fallback.
getOrBool
pub fn getOrBool(self: *const ParseResult, name: []const u8, default: bool) boolGets a boolean value with a default fallback.
getOrFloat
pub fn getOrFloat(self: *const ParseResult, name: []const u8, default: f64) f64Gets a float value with a default fallback.
getOrUint
pub fn getOrUint(self: *const ParseResult, name: []const u8, default: u64) u64Gets an unsigned integer value with a default fallback.
contains
pub fn contains(self: *const ParseResult, name: []const u8) boolChecks if a value exists.
getKeyValue
pub fn getKeyValue(self: *const ParseResult, name: []const u8) ?KeyValueGets a parsed KeyValue pair value (returned by addKeyValueOption).
getDuration
pub fn getDuration(self: *const ParseResult, name: []const u8) ?u64Gets the parsed duration in seconds (returned by addDurationOption).
getSize
pub fn getSize(self: *const ParseResult, name: []const u8) ?u64Gets the parsed byte-size in bytes (returned by addSizeOption).
hasSubcommand
pub fn hasSubcommand(self: *const ParseResult) boolChecks whether a subcommand was successfully matched and parsed.
isPresent
pub fn isPresent(self: *const ParseResult, name: []const u8) boolChecks if an argument was explicitly provided (either by user input or active defaults applied at parse time).
deinit
pub fn deinit(self: *ParseResult) voidReleases resources.
Complete Example
const std = @import("std");
const args = @import("args");
pub fn main(init: std.process.Init) !void {
const allocator = init.arena.allocator();
var parser = try args.ArgumentParser.init(allocator, .{
.name = "example",
.version = "1.0.0",
.description = "Example application",
});
defer parser.deinit();
try parser.addFlag("verbose", .{ .short = 'v' });
try parser.addOption("output", .{ .short = 'o', .default = "out.txt" });
try parser.addPositional("input", .{});
var result = try parser.parseProcess(init);
defer result.deinit();
const verbose = result.getBool("verbose") orelse false;
const output = result.getString("output").?;
const input = result.getString("input").?;
std.debug.print("Input: {s}, Output: {s}, Verbose: {}\n", .{
input, output, verbose
});
}