From 47cf241b4b03d728e8e4155418b09fdb5fe553b5 Mon Sep 17 00:00:00 2001 From: Gustav Behm Date: Fri, 29 Mar 2024 04:42:01 +0100 Subject: [PATCH] Parse options --- c-impl/action.c | 59 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/c-impl/action.c b/c-impl/action.c index 49e0ea8..b29fe21 100644 --- a/c-impl/action.c +++ b/c-impl/action.c @@ -5,6 +5,62 @@ #define LIBR_IMPLEMENTATION #include "r.h" +struct options { + const char* action; + + enum { + NOOP = 0, + BIND, + TRIGGER, + } cmd; +}; + +static void print_usage(int fd, const char* prog) +{ + dprintf(fd, "usage: %s [OPTION]... ACTION\n", prog); + dprintf(fd, "\n"); + dprintf(fd, "commands:\n"); + dprintf(fd, " -b bind action\n"); + dprintf(fd, " -t trigger action\n"); + dprintf(fd, " -h print this message\n"); +} + +static void parse_options(struct options* o, int argc, char* argv[]) +{ + memset(o, 0, sizeof(*o)); + + int res; + while((res = getopt(argc, argv, "bth")) != -1) { + switch(res) { + case 't': o->cmd = TRIGGER; break; + case 'b': o->cmd = BIND; break; + case 'h': + default: + print_usage(res == 'h' ? 1 : 2, argv[0]); + exit(res == 'h' ? 0 : 2); + } + } + + if(optind + 1 == argc) { + o->action = argv[optind]; + debug("action: %s", o->action); + } else { + if(optind >= argc) { + dprintf(2, "error: action not specified\n"); + } else { + dprintf(2, "error: too many actions specified\n"); + } + print_usage(2, argv[0]); + exit(2); + } + + if(o->cmd == NOOP) { + dprintf(2, "error: command not specified\n"); + print_usage(2, argv[0]); + exit(2); + } +} + struct state { int running; @@ -69,6 +125,9 @@ static void signalfd_handle_event(struct state* st) int main(int argc, char* argv[]) { + struct options o; + parse_options(&o, argc, argv); + struct state st = { .running = 1, }; -- 2.45.2