Skip to content

Commit 8aae3ae

Browse files
committed
Do not check environment variables if a subcommand has not been triggered.
1 parent 985a19f commit 8aae3ae

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

include/CLI/impl/App_inl.hpp

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1061,8 +1061,12 @@ CLI11_INLINE void App::_process_env() {
10611061
}
10621062

10631063
for(App_p &sub : subcommands_) {
1064-
if(sub->get_name().empty() || !sub->parse_complete_callback_)
1065-
sub->_process_env();
1064+
if (sub->get_name().empty() || !sub->parse_complete_callback_) {
1065+
if (sub->count_all() > 0) {
1066+
// only process environment variables if the callback has actually been triggered already
1067+
sub->_process_env();
1068+
}
1069+
}
10661070
}
10671071
}
10681072

tests/SubcommandTest.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2118,3 +2118,26 @@ TEST_CASE_METHOD(TApp, "DotNotationSubcommandRecusive2", "[subcom]") {
21182118
CHECK(extras.size() == 1);
21192119
CHECK(extras.front() == "sub1.sub2.sub3.bob");
21202120
}
2121+
2122+
// Reported bug #903 on github
2123+
TEST_CASE_METHOD(TApp, "subcommandEnvironmentName", "[subcom]") {
2124+
auto *sub1 = app.add_subcommand("sub1");
2125+
std::string someFile;
2126+
int sub1value{0};
2127+
sub1->add_option("-f,--file", someFile)->envname("SOME_FILE")->required()->check(CLI::ExistingFile);
2128+
sub1->add_option("-v",sub1value);
2129+
auto sub2 = app.add_subcommand("sub2");
2130+
int completelyUnrelatedToSub1 = 0;
2131+
sub2->add_option("-v,--value", completelyUnrelatedToSub1)->required();
2132+
2133+
args={"sub2","-v", "111"};
2134+
CHECK_NOTHROW(run());
2135+
2136+
put_env("SOME_FILE", "notafile.txt");
2137+
2138+
CHECK_NOTHROW(run());
2139+
2140+
args={"sub1","-v", "111"};
2141+
CHECK_THROWS_AS(run(), CLI::ValidationError);
2142+
unset_env("SOME_FILE");
2143+
}

0 commit comments

Comments
 (0)