From 7cddd3e1ea648b7c478c00559a23cc10417bc5dd Mon Sep 17 00:00:00 2001 From: Yaroslav de la Peña Smirnov Date: Fri, 12 Sep 2025 12:33:18 +0300 Subject: cli.h: a simple command-line parser A simple command-line commands and options parser. --- cli/cli-example.c | 110 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 cli/cli-example.c (limited to 'cli/cli-example.c') diff --git a/cli/cli-example.c b/cli/cli-example.c new file mode 100644 index 0000000..8149be0 --- /dev/null +++ b/cli/cli-example.c @@ -0,0 +1,110 @@ +/** + * silly simple example program + */ +#include "cli.h" + +long distance; +unsigned long time; +long speed; + +bool murica; + +int calc_speed(const struct cli_ctx *ctx) +{ + if (time == 0) { + fprintf(stderr, "time cannot be zero\n"); + return CLI_RC_BAD_ARGS; + } + double speed = (double)distance / ((double)time / 3600); + printf("%lf%s\n", speed, murica ? "mph" : "km/h"); + + return CLI_RC_OK; +} + +int calc_distance(const struct cli_ctx *ctx) +{ + double distance = speed * ((double)time / 3600); + printf("%lf%s\n", distance, murica ? "miles" : "km"); + + return CLI_RC_OK; +} + +const struct cli_opt speed_opts[] = { + { + .type = CLI_OT_INT, + .shor = 'd', + .lon = "distance", + .desc = "the distance (km/miles)", + .value.i = &distance, + }, + { + .type = CLI_OT_UINT, + .shor = 't', + .lon = "time", + .desc = "the time (seconds)", + .value.u = &time, + }, + {0}, +}; + +const struct cli_opt distance_opts[] = { + { + .type = CLI_OT_INT, + .shor = 's', + .lon = "speed", + .desc = "the speed ((km/miles)ph)", + .value.i = &speed, + }, + { + .type = CLI_OT_UINT, + .shor = 't', + .lon = "time", + .desc = "the time (seconds)", + .value.u = &time, + }, + {0}, +}; + +const struct cli_cmd my_cmds[] = { + { + .name = "speed", + .desc = "calculate speed", + .help = + "Tell me the distance and the time, and I'll tell you your speed", + .opts = speed_opts, + .func = calc_speed, + }, + { + .name = "distance", + .desc = "calculate distance", + .help = + "Tell me the speed and the time, and I'll tell you your distance", + .opts = distance_opts, + .func = calc_distance, + }, + {0}, +}; + +struct cli_opt global_opts[] = { + { + .type = CLI_OT_FLAG, + .shor = 'M', + .lon = "murica", + .desc = "Use American™ measurements", + .value.f = &murica, + }, + {0}, +}; + +struct cli my_cli = { + .header = "This is an example CLI program", + .footer = "\nCopyright (c) 2025 Yaroslav de la Peña Smirnov " + "", + .cmds = my_cmds, + .opts = global_opts, +}; + +int main(int argc, char *argv[]) +{ + return cli_run(&my_cli, argc, argv); +} -- cgit v1.2.3