Cmdline: use exceptions for control flow

This is generally frowned upon but it makes this code 10x cleaner.
We handle commandLine usage msg printing by using exceptions for
control flow. This allows us to centralize the logic for killing
the Mind threads in one place. At least with respect to printing
the usage msg.
This commit is contained in:
2025-08-13 09:43:34 -04:00
parent 7bee9b07ae
commit b6b2ce7ada
3 changed files with 86 additions and 32 deletions
+28 -6
View File
@@ -1,6 +1,7 @@
#include <opts.h>
#include <iostream>
#include <stdexcept>
#include <exception>
#include <getopt.h>
#include <string>
#include <vector>
@@ -8,6 +9,28 @@
#include <sstream>
OptionsParserError::OptionsParserError(
const std::string& errorMessage, const OptionParser& parser
)
: std::invalid_argument(errorMessage + "\n" + parser.getUsage())
{
}
const char* OptionsParserError::what() const noexcept
{
return std::invalid_argument::what();
}
JustPrintUsageNoError::JustPrintUsageNoError(const OptionParser& parser)
: message(parser.getUsage())
{
}
const char* JustPrintUsageNoError::what() const noexcept
{
return message.c_str();
}
struct option OptionParser::longOptions[] = {
{"devicespec", required_argument, 0, 's'},
{"spec", required_argument, 0, 's'},
@@ -59,9 +82,9 @@ void OptionParser::parseArguments(int argc, char *argv[], char **envp)
if (stat(optarg, &info) != 0 || !(info.st_mode & S_IFDIR))
{
throw std::invalid_argument(
throw OptionsParserError(
std::string(__func__) + " - The specified path is not a "
"directory: " + optarg);
"directory: " + optarg, *this);
}
senseApiLibPath.push_back(optarg);
@@ -71,12 +94,11 @@ void OptionParser::parseArguments(int argc, char *argv[], char **envp)
verbose = true;
break;
case 'h':
printUsage = true;
return;
throw JustPrintUsageNoError(*this);
case '?':
throw std::invalid_argument(
throw OptionsParserError(
std::string(__func__) + " - Invalid argument encountered: "
+ std::string(argv[optind - 1]));
+ std::string(argv[optind - 1]), *this);
}
}
}