Add ArgumentParser::parseArgsOrExit()
to reduce boilerplate code for error handling when parsing CLI arguments.
This commit is contained in:
parent
1c450d43a2
commit
2f5f197b95
|
@ -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.
|
||||
* \remarks
|
||||
|
|
|
@ -243,6 +243,7 @@ public:
|
|||
void addMainArgument(Argument *argument);
|
||||
void printHelp(std::ostream &os) const;
|
||||
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 resetArgs();
|
||||
unsigned int actualArgumentCount() const;
|
||||
|
|
|
@ -1,5 +1,9 @@
|
|||
#include "./failure.h"
|
||||
|
||||
#include "../io/ansiescapecodes.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
namespace ApplicationUtilities {
|
||||
|
||||
/*!
|
||||
|
@ -41,4 +45,16 @@ const char *Failure::what() const USE_NOTHROW
|
|||
{
|
||||
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
|
||||
|
|
|
@ -4,6 +4,7 @@
|
|||
#include "../global.h"
|
||||
|
||||
#include <exception>
|
||||
#include <iosfwd>
|
||||
#include <string>
|
||||
|
||||
namespace ApplicationUtilities {
|
||||
|
@ -19,6 +20,9 @@ public:
|
|||
private:
|
||||
std::string m_what;
|
||||
};
|
||||
|
||||
std::ostream &operator<<(std::ostream &o, const Failure &failure);
|
||||
|
||||
} // namespace ApplicationUtilities
|
||||
|
||||
#endif // APPLICATION_UTILITIES_FAILURE_H
|
||||
|
|
Loading…
Reference in New Issue