From 9ab4eb97fe3932a6485a5bff163045777014cff1 Mon Sep 17 00:00:00 2001 From: anon Date: Tue, 20 Jun 2023 14:01:51 +0200 Subject: [PATCH] working cli prototype --- Makefile | 2 +- src/setopt.cpp | 65 ++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 64 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 48c8451..a1758bd 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ main: - g++ -I lib/ src/setopt.cpp -o setopt + g++ -I lib/ src/setopt.cpp -o setopt -g test: test_template test_compile diff --git a/src/setopt.cpp b/src/setopt.cpp index e2d84d9..46606ed 100644 --- a/src/setopt.cpp +++ b/src/setopt.cpp @@ -1,7 +1,68 @@ #include +#include #include #include "setopt.hpp" -signed main(){ - return 0; +#define EXECUTABLE_NAME "setopt" + +const char HELP_MSG[] = "\ +%s : \n\ +\t-s : specify optstring\n\ +\t-j : read arguments from JSON string\n\ +\t-h : print help message and quit\n\ +"; + + + +using json = nlohmann::json; +using namespace std; + + + +void usage(){ + printf(HELP_MSG, EXECUTABLE_NAME); +} + +[[ noreturn ]] inline void die(){ + usage(); + exit(1); +} + +char* json_str = nullptr; +bool done_something = false; +unordered_map g_argv; +const char* g_optstring = nullptr; + +void parse_args(int argc, char** argv){ + char opt; + while((opt = getopt(argc, argv, "j:s:h")) != -1){ + switch(opt){ + case 'j': + json_str = strdup(optarg); + break; + case 's': + g_optstring = strdup(optarg); + break; + case 'h': + usage(); + exit(0); + } + done_something = true; + } + if(not done_something){ die(); } +} + +signed main(int argc, char** argv){ + parse_args(argc, argv); + + if(json_str){ + json j = json::parse(json_str); + for(const auto &i : j.items()){ + g_argv[i.key()[0]] = i.value(); + } + } + + if(not g_optstring){ die(); } + + puts(setopt(g_optstring, g_argv)); }