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.
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,
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,
deprecated: ?[]const u8 = null,
}) !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,
}) !voidAdds a positional argument.
Example:
try parser.addPositional("input", .{
.help = "Input file",
.required = true,
});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",
});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.
Example:
try parser.addAppend("include", .{
.short = 'I',
.help = "Include path (can be repeated)",
});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,
});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) !ParseResultParses arguments from the current process.
Example:
var result = try parser.parseProcess();
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,
) !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 args
Example:
const Config = struct {
verbose: bool,
output: ?[]const u8,
count: i32,
};
var result = try args.parseInto(allocator, Config, .{
.name = "myapp",
}, null);
defer result.deinit();
std.debug.print("Count: {d}\n", .{result.options.count});Function Aliases ​
For convenience, the library provides several aliases:
| Alias | Original Function | Description |
|---|---|---|
derive | parseInto | Parse args directly into a struct |
configure | initConfig | Set global configuration |
version | getLibraryVersion | Get library version string |
Example:
// These are equivalent:
var parsed = try args.parseInto(allocator, Config, options, null);
var parsed = try args.derive(allocator, Config, options, null);
// 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, no update check).
Example:
var parser = try args.createMinimalParser(allocator, "myapp");
defer parser.deinit();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.ArrayListUnmanaged([]const u8),
remaining: std.ArrayListUnmanaged([]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.
contains ​
pub fn contains(self: *const ParseResult, name: []const u8) boolChecks if a value exists.
deinit ​
pub fn deinit(self: *ParseResult) voidReleases resources.
Complete Example ​
const std = @import("std");
const args = @import("args");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.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();
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
});
}