Skip to content

Commit

Permalink
resolve compatibility with old ctor
Browse files Browse the repository at this point in the history
  • Loading branch information
eseiler committed Feb 9, 2024
1 parent fc1f255 commit 17e7727
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
13 changes: 9 additions & 4 deletions include/sharg/parser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -681,8 +681,9 @@ class parser
*/
parser_meta_data info;

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

auto & parser_subcommands = this->subcommands;
parser_subcommands.emplace_back(std::move(subcommand));
parser_subcommands.emplace_back(subcommand);

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

init();

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

private:
Expand Down
4 changes: 2 additions & 2 deletions test/snippet/readme_sneak_peek.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

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

if (auto pull_parser = git_parser.add_subcommand("pull"))
{
Expand Down
2 changes: 1 addition & 1 deletion test/unit/parser/parser_design_error_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ TEST(parse_test, subcommand_parser_error)
EXPECT_NO_THROW(top_level_parser.parse());
EXPECT_EQ(true, flag_value);

EXPECT_THROW(top_level_parser.get_sub_parser(), sharg::design_error);
EXPECT_THROW(std::ignore = top_level_parser.get_sub_parser(), sharg::design_error);
}

// subcommand key word must only contain alpha numeric characters
Expand Down

0 comments on commit 17e7727

Please sign in to comment.