Command Line Argument parser for Zig
- Subcommands, options, positional arguments, argument groups
- Compile-time CLI definition validation
- Help generation
- User error handling
- Shell completion generation (bash, zsh, fish)
- Suggestions for typos
zig fetch --save git+https://github.com/lepton9/zcli
In build.zig
const zcli = b.dependency("zcli", .{
.target = target,
.optimize = optimize,
.version_tag = @import("build.zig.zon").version,
});
const zcli_mod = zcli.module("zcli");
exe.root_module.addImport("zcli", zcli_mod);const zcli = @import("zcli");
const app: zcli.CliApp = .{
.config = .{
.name = "demo",
.description = null, // About text
.suggestions = false, // Turn on suggestions for typos
.auto_help = true, // Handle '--help' option
.auto_version = true, // Handle '--version' option
.help_max_width = 80, // Max amount of text on a line
},
.commands = &[_]zcli.Cmd{.{
.name = "command",
.desc = "Description",
.options = null,
.positionals = null,
.action = null,
}},
.options = &[_]zcli.Opt{
.{ .long_name = "option", .short_name = "o", .desc = "Description", .arg = .{ .name = "arg" } },
.{ .long_name = "version", .short_name = "v", .desc = "Print version" },
.{ .long_name = "help", .short_name = "h", .desc = "Print help" },
},
.positionals = &[_]zcli.PosArg{
.{ .name = "positional", .desc = "Description", .required = true, .multiple = false },
},
};Generated help text
$ demo --help
Usage: demo [command] [options]
Commands:
command Description
Options:
-o, --option <arg> Description
-V, --version Print version
-h, --help Print help
const std = @import("std");
const zcli = @import("zcli");
const app: zcli.CliApp = .{
// ...
};
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa = init.gpa;
// const cli: *zcli.Cli = try zcli.parseInit(init, &app);
const cli: *zcli.Cli = try zcli.parseArgs(io, gpa, init.minimal.args, &app);
defer cli.deinit(gpa);
// Find options
if (cli.findOption("option")) |option| {
std.debug.print(
"Option '{s}' value was: '{s}'\n",
.{ option.name, option.value.?.string },
);
}
// Generate shell completion scripts
var buffer: [4096]u8 = undefined;
const completions = try zcli.complete.getCompletion(
&buffer,
&app,
app.name,
"bash",
);
}Handling the CLI parsing errors manually:
// ...
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const args = try init.minimal.args.toSlice(init.arena.allocator());
const cli: *zcli.Cli = try zcli.parseFrom(gpa, args, &app);
defer cli.deinit(gpa);
}