A simple CLI parser building CLI applications in Zig
Usage | Building the CLI | Examples | Optionals | Default Values | Help Menu | What is not supported
Add snek to your Zig project with Zon:
zig fetch --save https://github.com/BitlyTwiser/snek/archive/refs/tags/v0.1.0.tar.gz
Add the following to build.zig file:
const snek = b.dependency("snek", .{});
exe.root_module.addImport("snek", snek.module("snek"));
Snek builds dynamic (yet simple) CLI's using zigs meta programming to infer the struct fields, the expected types, then insert the incoming data from the stdin arguments and serialize that data into the given struct mapping the data values to the given fields and marshalling the data into the proper type.
const T = struct {
bool_test: bool,
word: []const u8,
test_opt: ?u32,
test_default: []const u8 = "I am static if not set by user",
};
var snek = try Snek(T).init(std.heap.page_allocator);
const parsed = try snek.parse();
// Do Stuff with the fields of the struct after parsing
std.debug.print("{any}", .{parsed});
When the user goes to interact with the application, they can now utilize the flags you have established to run specific commands.
See the completed and functional example below or checkout the main file in the repo for a full working example as well.
- If the user does not supply a value and the field is not otional, that is a failure case and a message is displayed to the user
- If there is a default value on the field of the struct and a vale is not passed for that field, it is treated as an optional case and will use the static value (i.e. no error message and value is set)
- Simple structs only for now, no recursive struct fields at the moment. (i.e. no embeded structs)
- If the users passed the wrong type which differes from what is expeected (i.e. the type of the struct field), this is an error case and a message will be displayed to the user.
- If you want to handle the errors yourself, the CliError struct is public, so you can catch errors on the
parse()
call
const T = struct {
bool_test: bool,
word: []const u8,
test_opt: ?u32,
test_default: []const u8 = "I am static if not set by user",
};
var snek = try Snek(T).init(std.heap.page_allocator);
// Adjust to actually use value of course
_ = snek.parse() catch |err| {
switch(e) {
... do stuff with the Errors
}
}
Using the above struct as a reference, here are a few examples of calling the CLI:
./<yourappname> -help
# or
./<yourappname> -h
Note: As you can see, the optionals are just that, optional. They are not required by your users and can be checked in the calling code in the standard ways that Zig handles optionals. This is a design decisions allowing flexibility over the CLI to not lock users into using every flag etc..
./<yourappname> -bool_test=true -word="I am a word!"
./<yourappname> -bool_test=true -word="I am a word!"
# or to override the default field
./<yourappname> -bool_test=true -word="I am a word!" -test_defaults="I am a different word!"
const std = @import("std");
const snek = @import("lib.zig").Snek;
// Binary is also compiled for showcasing how to use the API
const T = struct {
name: []const u8,
location: u32,
exists: bool,
necessary: ?bool,
filled_optional: ?[]const u8,
default_name: []const u8 = "test default name",
};
// Example command after compilation:
// ./zig-out/bin/snek -name="test mctest" -location=420 -exists=true
pub fn main() !void {
var cli = try snek(T).init(std.heap.page_allocator);
const parsed_cli = try cli.parse();
// Necessary is skipped here to showcase optional values being ignored
std.debug.print("Name: {s}\n Location: {d}\n Exists: {any}\n Defualt value: {s}\n Filled Optional: {s}\n", .{ parsed_cli.name, parsed_cli.location, parsed_cli.exists, parsed_cli.default_name, parsed_cli.filled_optional orelse "badvalue" });
}
Compile with zig build
then run the cli command:
./zig-out/bin/snek -name="test mctest" -location=420 -exists=true
Using zig optionals, you can set selected flags to be ignored on the CLI, thus giving flexibilitiy on the behalf of the CLI creator to use or not use selected flags at their whimsy
You can use struct defaut values to set a static value if one is not parsed. This can be useful for certain flags for conditional logic branching later in program execution.
Snek dynaically builds the help menu for your users. By calling the help()
function, you can display how to use your CLI:
const T = struct {
bool_test: bool,
word: []const u8,
test_opt: ?u32,
};
var snek = try Snek(T).init(std.heap.page_allocator);
const parsed = try snek.help();
Output:
CLI Flags Help Menu
---------
-bool_test=Bool (optional: false)
-word=Pointer (optional: false)
-test_opt=Optional (optional: true)
---------
Alternatively, if users call -help as the first arguments in the CLI, it will also display the help menu.
./<yourappname> -help
# or
./<yourappname> -h
This will display the help menu and skip all other parsing. So its important to note that this is effectively an exit case for the parser and your program. You should build your application to support this.
At this time, no recursive flags are supported, i.e. you cannot use a slice of structs as a field in the primary CLI interface struct and have those fields parsed as sub-command fields. Perhaps, if this is requested, we could work that into the application. It seemed slightly messy and unecessray for a simple CLI builder, but perhaps expansion will be necessary there if its requested :)