From dc4fcc10ce14f34397fc53719a53d2da0306d3dd Mon Sep 17 00:00:00 2001 From: Riyyi Date: Tue, 7 Sep 2021 16:53:46 +0200 Subject: [PATCH] Util+Test: Implement exit on first error in main ArgParser loop --- src/util/argparser.cpp | 4 ++++ test/testutilargparser.cpp | 29 +++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/util/argparser.cpp b/src/util/argparser.cpp index 9121f8c..2d87884 100644 --- a/src/util/argparser.cpp +++ b/src/util/argparser.cpp @@ -241,6 +241,10 @@ bool ArgParser::parse(int argc, const char* argv[]) } printf("-> argu: '%s'", argument.data()); } + + if (m_exitOnFirstError && !result) { + break; + } } return result; diff --git a/test/testutilargparser.cpp b/test/testutilargparser.cpp index 772c7cf..f61a010 100644 --- a/test/testutilargparser.cpp +++ b/test/testutilargparser.cpp @@ -461,8 +461,8 @@ TEST_CASE(VectorStringOptions) EXPECT_EQ(result, true); EXPECT_EQ(vectorOpt1.size(), 2); if (vectorOpt1.size() == 2) { - EXPECT_EQ(vectorOpt1[0], "hello"); - EXPECT_EQ(vectorOpt1[1], "world"); + EXPECT_EQ(vectorOpt1.at(0), "hello"); + EXPECT_EQ(vectorOpt1.at(1), "world"); } } @@ -590,4 +590,29 @@ TEST_CASE(StopOnFirstNonOption) EXPECT_EQ(result, true); EXPECT_EQ(boolOpt1, true); EXPECT_EQ(boolOpt2, false); + +// ----------------------------------------- + +TEST_CASE(ExitOnFirstError) +{ + // Do not stop on first error, one non-existing given + // Expected: parsing fails, boolOpt1 is set + bool boolOpt1 = false; + auto result = runParser({ "--this-doesnt-exist", "--this-exist" }, [&](auto& parser) { + parser.setExitOnFirstError(false); + parser.addOption(boolOpt1, '\0', "this-exist", nullptr, nullptr); + }); + EXPECT_EQ(result, false); + EXPECT_EQ(boolOpt1, true); + + // Stop on first error, one non-existing given + // Expected: parsing fails, boolOpt1 is not set + boolOpt1 = false; + result = runParser({ "--this-doesnt-exist", "--this-exist" }, [&](auto& parser) { + parser.setExitOnFirstError(true); + parser.addOption(boolOpt1, '\0', "this-exist", nullptr, nullptr); + }); + EXPECT_EQ(result, false); + EXPECT_EQ(boolOpt1, false); +} }