From 878e63cd08975d1126f6a7c72f0d1fb847989b2f Mon Sep 17 00:00:00 2001 From: cobrapitz <12397702+cobrapitz@users.noreply.github.com> Date: Mon, 8 May 2023 00:36:22 +0200 Subject: [PATCH] feat: added help message feat: better error handling --- include/cb/argparser/argument_parser.h | 3 +++ src/cb/argparser/argument_parser.cpp | 27 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/include/cb/argparser/argument_parser.h b/include/cb/argparser/argument_parser.h index f63ad0c..fe518db 100644 --- a/include/cb/argparser/argument_parser.h +++ b/include/cb/argparser/argument_parser.h @@ -14,6 +14,7 @@ #include + namespace cb::argparser { using ArgumentMapType = std::unordered_map; @@ -51,6 +52,8 @@ public: ArgumentMap parse(int argc, char *argv[]); + std::string get_help(); + private: static void insert_argument(ArgumentMap &parsed_args, ParseArgument &positional_arg, const Argument &argument); diff --git a/src/cb/argparser/argument_parser.cpp b/src/cb/argparser/argument_parser.cpp index b51783c..5e301aa 100644 --- a/src/cb/argparser/argument_parser.cpp +++ b/src/cb/argparser/argument_parser.cpp @@ -1,6 +1,8 @@ #include "cb/argparser/argument_parser.h" +#include + cb::argparser::Argument::Argument(std::string content, cb::argparser::Type type) : content{std::move(content)}, type{type} { if (type == Type::BOOL_TYPE && this->content == "false") { @@ -179,3 +181,28 @@ void cb::argparser::ArgumentParser::add_argument(const std::string &short_name, assert(type == Type::INTEGER_TYPE); add_argument(short_name, name, type, std::move(description), std::to_string(default_value), mode); } + +std::string cb::argparser::ArgumentParser::get_help() { + std::string help_message{}; + if (not positional_arguments.empty()) { + help_message += "Positional Arguments:\n"; + for (auto &&arg: positional_arguments) { + help_message += std::format("{:15} {}\n", + arg.name, + arg.description); + } + help_message += "\n"; + } + + if (not arguments.empty()) { + help_message += "Arguments:\n"; + for (auto &&arg: arguments) { + help_message += std::format("{:5} {:15} {}\n", + arg.short_name, + arg.name, + arg.description); + } + help_message += "\n"; + } + return help_message; +}