Skip to content

Commit

Permalink
Do not check environment variables if a subcommand has not been trigg…
Browse files Browse the repository at this point in the history
…ered.
  • Loading branch information
phlptp committed Jul 9, 2023
1 parent 985a19f commit 8aae3ae
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
8 changes: 6 additions & 2 deletions include/CLI/impl/App_inl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1061,8 +1061,12 @@ CLI11_INLINE void App::_process_env() {
}

for(App_p &sub : subcommands_) {
if(sub->get_name().empty() || !sub->parse_complete_callback_)
sub->_process_env();
if (sub->get_name().empty() || !sub->parse_complete_callback_) {
if (sub->count_all() > 0) {
// only process environment variables if the callback has actually been triggered already
sub->_process_env();
}
}
}
}

Expand Down
23 changes: 23 additions & 0 deletions tests/SubcommandTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2118,3 +2118,26 @@ TEST_CASE_METHOD(TApp, "DotNotationSubcommandRecusive2", "[subcom]") {
CHECK(extras.size() == 1);
CHECK(extras.front() == "sub1.sub2.sub3.bob");
}

// Reported bug #903 on github
TEST_CASE_METHOD(TApp, "subcommandEnvironmentName", "[subcom]") {
auto *sub1 = app.add_subcommand("sub1");
std::string someFile;
int sub1value{0};
sub1->add_option("-f,--file", someFile)->envname("SOME_FILE")->required()->check(CLI::ExistingFile);
sub1->add_option("-v",sub1value);
auto sub2 = app.add_subcommand("sub2");
int completelyUnrelatedToSub1 = 0;
sub2->add_option("-v,--value", completelyUnrelatedToSub1)->required();

args={"sub2","-v", "111"};
CHECK_NOTHROW(run());

put_env("SOME_FILE", "notafile.txt");

CHECK_NOTHROW(run());

args={"sub1","-v", "111"};
CHECK_THROWS_AS(run(), CLI::ValidationError);
unset_env("SOME_FILE");
}

0 comments on commit 8aae3ae

Please sign in to comment.