-
-
Save TheWaWaR/9c4dde075291ed9484f0aca87c47528a to your computer and use it in GitHub Desktop.
A clap-rs inspired command line argument parser design for zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const print = @import("std").debug.print; | |
const clap = @import("clap"); | |
const Arg = clap.Arg; | |
const Subcommand = clap.Subcommand; | |
const Cli = clap.Parser(struct { | |
name: Arg(?[]const u8, .{ | |
.short = "n", | |
.help = "Optional name to operate on", | |
}), | |
debug: Arg(u8, .{ | |
.short = "d", | |
.help = "Turn debugging information on", | |
}), | |
command: ?Commands, | |
}, .{ | |
.about = "This is a test program", | |
.long_about = "This is a test program, to fuzz test zig program", | |
}); | |
const Commands = union(enum) { | |
@"test": Subcommand(struct { | |
list: Arg(bool, .{ | |
.short = "l", | |
.help = "lists test values", | |
}), | |
command: ?TestCommands, | |
}, .{ | |
.help = "does testing things", | |
}), | |
start: Subcommand(struct { | |
config: Arg([]const u8, .{ | |
.short = "c", | |
.parser = config_parser, | |
.help = "The config file path", | |
}), | |
}, .{ | |
.help = "Start the server", | |
}), | |
}; | |
const TestCommands = union(enum) { | |
simple: Subcommand(struct { | |
arg1: Arg([]const u8, .{}), | |
arg2: Arg(u32, .{ .parser = u32_parser }), | |
}, .{ | |
.help = "Show simple test report", | |
}), | |
full: Subcommand(struct { | |
arg1: Arg([]const u8, .{}), | |
arg2: Arg(u32, .{}), | |
}, .{ | |
.help = "Show full test report", | |
}), | |
}; | |
fn config_parser(input: []const u8) ![]const u8 { | |
return error.InvalidConfig; | |
} | |
fn u32_parser(input: []const u8) !u32 { | |
return error.InvalidNumber; | |
} | |
pub fn main() !void { | |
const cli = Cli.parse(); | |
print("name: {}, debug: {}\n", .{ cli.name, cli.debug }); | |
if (cli.command) |commands| { | |
switch (commands) { | |
.@"test" => |cmd| { | |
print("test with list: {}", .{cmd.list}); | |
if (cmd.command) |sub_cmds| { | |
switch (sub_cmds) { | |
.simple => |sub_cmd| { | |
print("test simple, arg1: {}, arg2: {}\n", .{ sub_cmd.arg1, sub_cmd.arg2 }); | |
}, | |
.full => |sub_cmd| { | |
print("test full, arg1: {}, arg2: {}\n", .{ sub_cmd.arg1, sub_cmd.arg2 }); | |
}, | |
} | |
} | |
}, | |
.start => |cmd| { | |
print("start server, {}\n", .{cmd.config}); | |
}, | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment