From 39c720e6c094b959f6916ed5ea2b465a041f12c0 Mon Sep 17 00:00:00 2001 From: Mio Date: Tue, 6 Aug 2019 20:48:51 +0800 Subject: [PATCH 1/2] Add a mIsRquired field --- include/argparse.hpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/include/argparse.hpp b/include/argparse.hpp index 7411918..96e453d 100644 --- a/include/argparse.hpp +++ b/include/argparse.hpp @@ -102,6 +102,11 @@ public: return *this; } + Argument& required() { + mIsRequired = true; + return *this; + } + Argument& implicit_value(std::any aImplicitValue) { mImplicitValue = std::move(aImplicitValue); mNumArgs = 0; @@ -158,6 +163,16 @@ public: } else { // TODO: check if an implicit value was programmed for this argument + if (!mIsUsed && !mDefaultValue.has_value() && mIsRequired) { + std::stringstream stream; + stream << "error: " << mNames[0] << ": required."; + throw std::runtime_error(stream.str()); + } + if (mIsUsed && mIsRequired && mValues.size() == 0) { + std::stringstream stream; + stream << "error: " << mUsedName << ": no value provided."; + throw std::runtime_error(stream.str()); + } } } else { @@ -298,6 +313,7 @@ public: std::vector mRawValues; size_t mNumArgs = 1; bool mIsOptional = false; + bool mIsRequired = false; bool mIsUsed = false; // relevant for optional arguments. True if used by user public: From 47122880860507d0433482e2d3ae34d1a3d243db Mon Sep 17 00:00:00 2001 From: Mio Date: Tue, 6 Aug 2019 20:52:31 +0800 Subject: [PATCH 2/2] Change the format of required arguments --- include/argparse.hpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/include/argparse.hpp b/include/argparse.hpp index 96e453d..bece74c 100644 --- a/include/argparse.hpp +++ b/include/argparse.hpp @@ -194,7 +194,11 @@ public: friend std::ostream& operator<<(std::ostream& stream, const Argument& argument) { std::stringstream nameStream; std::copy(std::begin(argument.mNames), std::end(argument.mNames), std::ostream_iterator(nameStream, " ")); - return stream << nameStream.str() << "\t" << argument.mHelp << "\n"; + stream << nameStream.str() << "\t" << argument.mHelp; + if (argument.mIsRequired) + stream << "[Required]"; + stream << "\n"; + return stream; }