Add ArgumentParser::parseArgsOrExit()

to reduce boilerplate code for error handling when
parsing CLI arguments.
This commit is contained in:
Martchus 2017-09-29 17:14:57 +02:00
parent 1c450d43a2
commit 2f5f197b95
4 changed files with 39 additions and 0 deletions

View File

@ -684,6 +684,24 @@ void ArgumentParser::parseArgs(int argc, const char *const *argv)
} }
} }
/*!
* \brief Parses the specified command line arguments.
* \remarks The same as parseArgs(), except that this method will not throw an exception in the error
* case. Instead, it will print an error message and terminate the application with exit
* code 1.
* \sa parseArgs(), readArgs()
*/
void ArgumentParser::parseArgsOrExit(int argc, const char *const *argv)
{
try {
parseArgs(argc, argv);
} catch (const Failure &failure) {
CMD_UTILS_START_CONSOLE;
cerr << failure;
exit(1);
}
}
/*! /*!
* \brief Parses the specified command line arguments. * \brief Parses the specified command line arguments.
* \remarks * \remarks

View File

@ -243,6 +243,7 @@ public:
void addMainArgument(Argument *argument); void addMainArgument(Argument *argument);
void printHelp(std::ostream &os) const; void printHelp(std::ostream &os) const;
void parseArgs(int argc, const char *const *argv); void parseArgs(int argc, const char *const *argv);
void parseArgsOrExit(int argc, const char *const *argv);
void readArgs(int argc, const char *const *argv); void readArgs(int argc, const char *const *argv);
void resetArgs(); void resetArgs();
unsigned int actualArgumentCount() const; unsigned int actualArgumentCount() const;

View File

@ -1,5 +1,9 @@
#include "./failure.h" #include "./failure.h"
#include "../io/ansiescapecodes.h"
#include <iostream>
namespace ApplicationUtilities { namespace ApplicationUtilities {
/*! /*!
@ -41,4 +45,16 @@ const char *Failure::what() const USE_NOTHROW
{ {
return m_what.c_str(); return m_what.c_str();
} }
/*!
* \brief Prints an error message "Unable to parse arguments: ..." for the specified \a failure.
*/
std::ostream &operator<<(std::ostream &o, const Failure &failure)
{
using namespace std;
using namespace EscapeCodes;
return o << Phrases::Error << "Unable to parse arguments: " << TextAttribute::Reset << failure.what() << "\nSee --help for available commands."
<< endl;
}
} // namespace ApplicationUtilities } // namespace ApplicationUtilities

View File

@ -4,6 +4,7 @@
#include "../global.h" #include "../global.h"
#include <exception> #include <exception>
#include <iosfwd>
#include <string> #include <string>
namespace ApplicationUtilities { namespace ApplicationUtilities {
@ -19,6 +20,9 @@ public:
private: private:
std::string m_what; std::string m_what;
}; };
std::ostream &operator<<(std::ostream &o, const Failure &failure);
} // namespace ApplicationUtilities } // namespace ApplicationUtilities
#endif // APPLICATION_UTILITIES_FAILURE_H #endif // APPLICATION_UTILITIES_FAILURE_H