CLI parser: support for parsing certain options first

This commit is contained in:
Moritz Bunkus 2022-03-27 11:15:35 +02:00
parent b843544a0c
commit 23f34b59e3
No known key found for this signature in database
GPG Key ID: 74AF00ADF2E32C85
2 changed files with 25 additions and 2 deletions

View File

@ -95,6 +95,12 @@ parser_c::parse_args() {
run_hooks(parser_c::ht_common_options_parsed);
parse_args_pass(true);
parse_args_pass(false);
}
void
parser_c::parse_args_pass(bool first_pass) {
for (auto sit = m_args.cbegin(), sit_end = m_args.cend(); sit != sit_end; sit++) {
auto sit_next = sit + 1;
auto no_next_arg = sit_next == sit_end;
@ -111,9 +117,11 @@ parser_c::parse_args() {
++sit;
}
option.m_callback();
if ( ( first_pass && m_parse_first[m_current_arg])
|| (!first_pass && !m_parse_first[m_current_arg]))
option.m_callback();
} else if (!run_hooks(parser_c::ht_unknown_option))
} else if (!first_pass && !run_hooks(parser_c::ht_unknown_option))
mxerror(fmt::format(Y("Unknown option '{0}'.\n"), m_current_arg));
}
}
@ -197,6 +205,17 @@ parser_c::set_usage() {
mtx::cli::g_usage_text += option.format_text();
}
void
parser_c::set_to_parse_first(std::vector<std::string> const &names) {
for (auto const &name : names)
m_parse_first[name] = true;
}
void
parser_c::set_to_parse_first(std::string const &name) {
m_parse_first[name] = true;
}
void
parser_c::dummy_callback() {
}

View File

@ -53,6 +53,7 @@ protected:
std::map<std::string, option_t> m_option_map;
std::vector<option_t> m_options;
std::vector<std::string> m_args;
std::unordered_map<std::string, bool> m_parse_first;
std::string m_current_arg, m_next_arg;
@ -71,7 +72,10 @@ protected:
void add_common_options();
void parse_args();
void parse_args_pass(bool first_pass);
void set_usage();
void set_to_parse_first(std::vector<std::string> const &names);
void set_to_parse_first(std::string const &name);
void dummy_callback();