aboutsummaryrefslogtreecommitdiff
path: root/cli/cli-example.c
diff options
context:
space:
mode:
authorYaroslav de la Peña Smirnov <yps@yaroslavps.com>2025-09-12 12:33:18 +0300
committerYaroslav de la Peña Smirnov <yps@yaroslavps.com>2025-09-12 12:33:18 +0300
commit7cddd3e1ea648b7c478c00559a23cc10417bc5dd (patch)
treea8db3f4c86f4fe36d84a469ce41e749e8d67755b /cli/cli-example.c
parent3620253a9463a9a256a2a031312d175fd23c73c1 (diff)
downloadc-wares-7cddd3e1ea648b7c478c00559a23cc10417bc5dd.tar.gz
c-wares-7cddd3e1ea648b7c478c00559a23cc10417bc5dd.zip
cli.h: a simple command-line parser
A simple command-line commands and options parser.
Diffstat (limited to 'cli/cli-example.c')
-rw-r--r--cli/cli-example.c110
1 files changed, 110 insertions, 0 deletions
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 "
+ "<yps@yaroslavps.com>",
+ .cmds = my_cmds,
+ .opts = global_opts,
+};
+
+int main(int argc, char *argv[])
+{
+ return cli_run(&my_cli, argc, argv);
+}