Skip to content

Commit

Permalink
[#2788] add RAII struct for exhausting options
Browse files Browse the repository at this point in the history
  • Loading branch information
andrei-pavel committed Jan 26, 2024
1 parent c3507eb commit a146a11
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
12 changes: 4 additions & 8 deletions src/lib/process/d_controller.cc
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,10 @@ DControllerBase::parseArgs(int argc, char* argv[]) {
opterr = 0;
optind = 1;
std::string opts("dvVWc:t:" + getCustomOpts());

// Defer exhausting of arguments to the end.
ExhaustOptions e(argc, argv, opts);

while ((ch = getopt(argc, argv, opts.c_str())) != -1) {
switch (ch) {
case 'd':
Expand Down Expand Up @@ -297,10 +301,6 @@ DControllerBase::parseArgs(int argc, char* argv[]) {
char const saved_optopt(optopt);
std::string const saved_optarg(optarg ? optarg : std::string());

// Exhaust all remaining options in case parseArgs() is called again.
while (getopt(argc, argv, opts.c_str()) != -1) {
}

// We hit an invalid option.
isc_throw(InvalidUsage, "unsupported option: -" << saved_optopt <<
(saved_optarg.empty() ? std::string() : " " + saved_optarg));
Expand All @@ -314,10 +314,6 @@ DControllerBase::parseArgs(int argc, char* argv[]) {
char const saved_optopt(optopt);
std::string const saved_optarg(optarg ? optarg : std::string());

// Exhaust all remaining options in case parseArgs() is called again.
while (getopt(argc, argv, opts.c_str()) != -1) {
}

// We hit an invalid option.
isc_throw(InvalidUsage, "unsupported option: -" << saved_optopt <<
(saved_optarg.empty() ? std::string() : " " + saved_optarg));
Expand Down
22 changes: 19 additions & 3 deletions src/lib/process/d_controller.h
Original file line number Diff line number Diff line change
Expand Up @@ -652,9 +652,25 @@ class DControllerBase : public Daemon {
/// @brief Singleton instance value.
static DControllerBasePtr controller_;

// DControllerTest is named a friend class to facilitate unit testing while
// leaving the intended member scopes intact.
friend class DControllerTest;
// DControllerTest is named a friend class to facilitate unit testing while
// leaving the intended member scopes intact.
friend class DControllerTest;

/// @brief Structure used in parseArgs() to reset arguments in case parseArgs() is called again.
struct ExhaustOptions {
ExhaustOptions(int argc, char* argv[], std::string opts)
: argc_(argc), argv_(argv), opts_(opts) {
}
~ExhaustOptions() {
while (getopt(argc_, argv_, opts_.c_str()) != -1) {
}
}

private:
int argc_;
char** argv_;
std::string opts_;
};
};

} // namespace process
Expand Down

0 comments on commit a146a11

Please sign in to comment.