Skip to content

Commit f28bc44

Browse files
authored
Merge pull request #190 from kkarbowiak/refactor2
Refactor code
2 parents 9801ad3 + cf38a82 commit f28bc44

1 file changed

Lines changed: 39 additions & 15 deletions

File tree

include/argparse.hpp

Lines changed: 39 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1899,32 +1899,22 @@ namespace argparse
18991899

19001900
~ArgumentBuilder() noexcept(false)
19011901
{
1902+
if (is_mutually_exclusive() && !is_allowed_in_mutually_exclusive_group())
1903+
{
1904+
throw option_error("mutually exclusive arguments must be optional");
1905+
}
1906+
19021907
if ((m_options.action == argparse::version) && m_options.help.empty())
19031908
{
19041909
m_options.help = "show program's version number and exit";
19051910
}
19061911

19071912
if (is_positional())
19081913
{
1909-
if (m_options.mutually_exclusive_group != nullptr
1910-
&& (!m_options.nargs.has_value()
1911-
|| (!std::holds_alternative<Nargs>(*m_options.nargs)
1912-
|| (std::get<Nargs>(*m_options.nargs) != zero_or_one
1913-
&& std::get<Nargs>(*m_options.nargs) != zero_or_more))))
1914-
{
1915-
throw option_error("mutually exclusive arguments must be optional");
1916-
}
1917-
19181914
m_arguments.emplace_back(PositionalArgument(std::move(m_options)));
19191915
}
19201916
else
19211917
{
1922-
if (m_options.mutually_exclusive_group != nullptr
1923-
&& m_options.required)
1924-
{
1925-
throw option_error("mutually exclusive arguments must be optional");
1926-
}
1927-
19281918
m_arguments.emplace_back(OptionalArgument(std::move(m_options)));
19291919
}
19301920
}
@@ -2025,6 +2015,40 @@ namespace argparse
20252015
return !m_options.names.front().starts_with('-');
20262016
}
20272017

2018+
auto is_mutually_exclusive() const -> bool
2019+
{
2020+
return m_options.mutually_exclusive_group != nullptr;
2021+
}
2022+
2023+
auto is_allowed_in_mutually_exclusive_group() const -> bool
2024+
{
2025+
if (is_positional())
2026+
{
2027+
return is_optional_by_nargs_option();
2028+
}
2029+
else
2030+
{
2031+
return !m_options.required;
2032+
}
2033+
}
2034+
2035+
auto is_optional_by_nargs_option() const -> bool
2036+
{
2037+
if (!m_options.nargs.has_value())
2038+
{
2039+
return false;
2040+
}
2041+
2042+
if (!std::holds_alternative<Nargs>(*m_options.nargs))
2043+
{
2044+
return false;
2045+
}
2046+
2047+
auto const nargs = std::get<Nargs>(*m_options.nargs);
2048+
2049+
return nargs == zero_or_one || nargs == zero_or_more;
2050+
}
2051+
20282052
private:
20292053
Arguments & m_arguments;
20302054
OptString & m_version;

0 commit comments

Comments
 (0)