API change: changed the "cli_parser_c::set_default_callback()" to a hook system.

This commit is contained in:
Moritz Bunkus 2009-08-11 12:31:01 +02:00
parent 36d21732a8
commit 090eab3dfd
3 changed files with 34 additions and 12 deletions

View File

@ -128,6 +128,8 @@ cli_parser_c::option_t::format_text() {
cli_parser_c::cli_parser_c(const std::vector<std::string> &args)
: m_args(args)
{
m_hooks[cli_parser_c::ht_common_options_parsed] = std::vector<cli_parser_cb_t>();
m_hooks[cli_parser_c::ht_unknown_option] = std::vector<cli_parser_cb_t>();
}
void
@ -136,6 +138,8 @@ cli_parser_c::parse_args() {
while (handle_common_cli_args(m_args, ""))
set_usage();
run_hooks(cli_parser_c::ht_common_options_parsed);
std::vector<std::string>::const_iterator sit;
mxforeach(sit, m_args) {
bool no_next_arg = (sit + 1) == m_args.end();
@ -154,10 +158,7 @@ cli_parser_c::parse_args() {
option.m_callback();
} else if (m_default_callback)
m_default_callback();
else
} else if (!run_hooks(cli_parser_c::ht_unknown_option))
mxerror(boost::format(Y("Unknown option '%1%'.\n")) % m_current_arg);
}
}
@ -225,11 +226,6 @@ cli_parser_c::add_common_options() {
#undef OPT
void
cli_parser_c::set_default_callback(cli_parser_cb_t callback) {
m_default_callback = callback;
}
void
cli_parser_c::set_usage() {
usage_text = "";
@ -242,3 +238,22 @@ void
cli_parser_c::dummy_callback() {
mxerror(boost::format("cli_parser_c::dummy_callback(): %1%") % BUGMSG);
}
void
cli_parser_c::add_hook(cli_parser_c::hook_type_e hook_type,
const cli_parser_cb_t &callback) {
m_hooks[hook_type].push_back(callback);
}
bool
cli_parser_c::run_hooks(cli_parser_c::hook_type_e hook_type) {
if (m_hooks[hook_type].empty())
return false;
std::vector<cli_parser_cb_t>::iterator hook_it;
mxforeach(hook_it, m_hooks[hook_type])
if (*hook_it)
(*hook_it)();
return true;
}

View File

@ -44,13 +44,18 @@ protected:
std::string format_text();
};
enum hook_type_e {
ht_common_options_parsed,
ht_unknown_option,
};
std::map<std::string, option_t> m_option_map;
std::vector<option_t> m_options;
std::vector<std::string> m_args;
std::string m_current_arg, m_next_arg;
cli_parser_cb_t m_default_callback;
std::map<hook_type_e, std::vector<cli_parser_cb_t> > m_hooks;
protected:
cli_parser_c(const std::vector<std::string> &args);
@ -61,11 +66,13 @@ protected:
void add_separator();
void add_common_options();
void set_default_callback(cli_parser_cb_t callback);
void parse_args();
void set_usage();
void dummy_callback();
void add_hook(hook_type_e hook_type, const cli_parser_cb_t &callback);
bool run_hooks(hook_type_e hook_type);
};
#endif // __COMMON_CLI_PARSER_H

View File

@ -97,7 +97,7 @@ propedit_cli_parser_c::init_parser() {
add_separator();
add_information(YT("The order of the various options is not important."));
set_default_callback(boost::bind(&propedit_cli_parser_c::set_file_name, this));
add_hook(cli_parser_c::ht_unknown_option, boost::bind(&propedit_cli_parser_c::set_file_name, this));
}
#undef OPT