Skip to content

Commit 17e7727

Browse files
committed
resolve compatibility with old ctor
1 parent fc1f255 commit 17e7727

3 files changed

Lines changed: 12 additions & 7 deletions

File tree

include/sharg/parser.hpp

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -681,8 +681,9 @@ class parser
681681
*/
682682
parser_meta_data info;
683683

684-
/*!\brief Adds subcommands to the parser.
685-
* \param[in] subcommands A list of subcommands.
684+
/*!\brief Adds a subcommand to the parser.
685+
* \param[in] subcommand The subcommand to add.
686+
* \returns A pointer to the sub-parser if subcommand is encountered, nullptr otherwise.
686687
* \throws sharg::design_error if the subcommand name contains illegal characters.
687688
*/
688689
[[nodiscard]] parser * add_subcommand(std::string subcommand)
@@ -701,15 +702,19 @@ class parser
701702
};
702703

703704
auto & parser_subcommands = this->subcommands;
704-
parser_subcommands.emplace_back(std::move(subcommand));
705+
parser_subcommands.emplace_back(subcommand);
705706

706707
std::ranges::sort(parser_subcommands);
707708
auto const [first, last] = std::ranges::unique(parser_subcommands);
708709
parser_subcommands.erase(first, last);
709710

710711
init();
711712

712-
return sub_parser.get();
713+
// If a subcommand was already added via the constructor, we need to check if the subcommand is the same.
714+
if (sub_parser && sub_parser->info.app_name == info.app_name + '-' + subcommand)
715+
return sub_parser.get();
716+
else
717+
return nullptr;
713718
}
714719

715720
private:

test/snippet/readme_sneak_peek.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
int main(int argc, char ** argv)
44
{
5-
// sharg::parser git_parser{"git", argc, argv, sharg::update_notifications::on, {"pull", "push", "remote"}}; // NOT ALLOWED
6-
sharg::parser git_parser{"git", argc, argv, sharg::update_notifications::on};
5+
// -------- Optional --------
6+
sharg::parser git_parser{"git", argc, argv, sharg::update_notifications::on, {"pull", "push", "remote"}};
77

88
if (auto pull_parser = git_parser.add_subcommand("pull"))
99
{

test/unit/parser/parser_design_error_test.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ TEST(parse_test, subcommand_parser_error)
263263
EXPECT_NO_THROW(top_level_parser.parse());
264264
EXPECT_EQ(true, flag_value);
265265

266-
EXPECT_THROW(top_level_parser.get_sub_parser(), sharg::design_error);
266+
EXPECT_THROW(std::ignore = top_level_parser.get_sub_parser(), sharg::design_error);
267267
}
268268

269269
// subcommand key word must only contain alpha numeric characters

0 commit comments

Comments
 (0)