From ccb268d2d186b50e8b7421008eb9ac0eb1ad4145 Mon Sep 17 00:00:00 2001 From: Pranav Srinivas Kumar Date: Sat, 30 Mar 2019 19:57:47 -0400 Subject: [PATCH] Checking if argument is positional and saving this as a property in Argument object --- src/argparse.hpp | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/argparse.hpp b/src/argparse.hpp index 3ed9faa..bfd3ef0 100644 --- a/src/argparse.hpp +++ b/src/argparse.hpp @@ -6,6 +6,7 @@ #include #include #include +#include namespace argparse { @@ -32,6 +33,11 @@ bool upsert(std::map& aMap, KeyType const& aKey, ElementTy return true; // changed cause not existing } +bool starts_with(const std::string& haystack, const std::string& needle) { + return needle.length() <= haystack.length() + && std::equal(needle.begin(), needle.end(), haystack.begin()); +}; + struct Argument { std::vector mNames; std::string mHelp; @@ -40,6 +46,7 @@ struct Argument { std::vector mValues; std::vector mRawValues; size_t mNumArgs; + bool mIsPositional; Argument() : mNames({}), @@ -47,7 +54,8 @@ struct Argument { mAction([](const std::string& aValue) { return aValue; }), mValues({}), mRawValues({}), - mNumArgs(1) {} + mNumArgs(1), + mIsPositional(false) {} Argument& help(const std::string& aHelp) { mHelp = aHelp; @@ -139,7 +147,16 @@ class ArgumentParser { std::shared_ptr tArgument = std::make_shared(); tArgument->mNames.push_back(value); add_argument_internal(tArgument, Fargs...); - mPositionalArguments.push_back(tArgument); // TODO: check if argument is positional before push_back + + bool positional = false; + for (auto& mName : tArgument->mNames) { + if (starts_with(mName, "--") || starts_with(mName, "-")) + tArgument->mIsPositional = true; + } + + if (tArgument->mIsPositional) + mPositionalArguments.push_back(tArgument); + for (auto& mName : tArgument->mNames) { upsert(mArgumentMap, mName, tArgument); }