From 822d926651c3c46db03337995498e053fa8705b5 Mon Sep 17 00:00:00 2001 From: Brett Date: Sun, 31 Mar 2024 01:42:38 -0400 Subject: [PATCH] argparse bug fix --- CMakeLists.txt | 2 +- include/blt/parse/argparse.h | 38 ++++++++++++++++++++++++++++-------- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a323888..191ee95 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.5) include(cmake/color.cmake) -set(BLT_VERSION 0.15.7) +set(BLT_VERSION 0.15.8) set(BLT_TEST_VERSION 0.0.1) set(BLT_TARGET BLT) diff --git a/include/blt/parse/argparse.h b/include/blt/parse/argparse.h index 0b16f48..d6ae34b 100644 --- a/include/blt/parse/argparse.h +++ b/include/blt/parse/argparse.h @@ -17,10 +17,11 @@ #include #include #include +#include "blt/std/utility.h" namespace blt { - typedef std::variant arg_data_internal_t; + typedef std::variant arg_data_internal_t; typedef std::vector arg_data_vec_t; typedef std::variant arg_data_t; @@ -307,8 +308,13 @@ namespace blt template static inline T get_cast(arg_data_t& v) { - if constexpr (std::is_same_v) - return std::get(v); + if (std::holds_alternative(v)) + { + if constexpr (std::is_same_v) + return std::get(v); + else + throw std::runtime_error("Cannot request singular data from stored vector type"); + } auto t = std::get(v); // user is requesting an int, but holds a string, we are going to make the assumption the data can be converted // it is up to the user to deal with the variant if they do not want this behaviour! @@ -319,12 +325,20 @@ namespace blt return static_cast(std::get(t)); if (std::holds_alternative(t)) return static_cast(std::get(t)); + auto s = std::get(t); + + if (s.empty()) + throw std::runtime_error("Key does not have value!"); + if constexpr (std::is_floating_point_v) return static_cast(std::stod(s)); - if constexpr (std::is_signed_v) + else if constexpr (std::is_signed_v) return static_cast(std::stoll(s)); - return static_cast(std::stoull(s)); + else if constexpr (std::is_unsigned_v) + return static_cast(std::stoull(s)); + else + return static_cast(s); } struct arg_results @@ -346,10 +360,17 @@ namespace blt template inline T get(const std::string& key) { - if constexpr (std::is_same_v) - return blt::arg_parse::get(data[key]); + hashmap_t::iterator val; + if (blt::string::starts_with(key, "--")) + val = data.find(key.substr(2)); + else if (blt::string::starts_with(key, '-')) + val = data.find(key.substr(1)); else - return blt::arg_parse::get_cast(data[key]); + val = data.find(key); + if constexpr (std::is_same_v) + return blt::arg_parse::get(val->second); + else + return blt::arg_parse::get_cast(val->second); } inline auto begin() @@ -371,6 +392,7 @@ namespace blt return data.find(key) != data.end(); } }; + private: struct {