|
- #pragma once
-
- #include <cppargs/parser/parser.h>
- #include <cppargs/group/group.inl>
- #include <cppargs/misc/printing.inl>
-
- namespace cppargs
- {
-
- parser::parser(
- option_ptr_type&& p_default,
- group& p_group)
- : _default (std::move(p_default))
- , _group (p_group)
- { }
-
- void parser::add_to_map(const group& g)
- {
- for (auto& o : g._options)
- {
- if (!o)
- throw std::runtime_error("expectd option to not be null!");
- if (o->meta.short_name)
- {
- if (!_map.emplace(std::string("-") + o->meta.short_name, o.get()).second)
- throw std::runtime_error(std::string("duplicate option key: ") + o->meta.short_name);
- }
- if (!o->meta.long_name.empty())
- {
- if (!_map.emplace(std::string("--") + o->meta.long_name, o.get()).second)
- throw std::runtime_error(std::string("duplicate option key: ") + o->meta.long_name);
- }
- }
-
- for (auto& i : g._groups)
- {
- if (!i)
- throw std::runtime_error("expectd group to not be null!");
- add_to_map(*i);
- }
- }
-
- void parser::update_map()
- {
- _map.clear();
- add_to_map(_group);
- }
-
- void parser::handle_invalid_arg(context& c) const
- {
- if (_default)
- {
- _default->parse(c);
- }
- else
- {
- throw std::runtime_error(std::string("invalid or unknown argument: ") + c.arg);
- }
- }
-
- void parser::parse(int argc, char const * argv[]) const
- {
- if (argc <= 0) {
- return;
- }
-
- context c
- {
- argc,
- argv,
- argv[0],
- };
-
- next_result ret;
- std::string key;
- while ((ret = c.next(&key)) != next_result::finished)
- {
- /* move to next option */
- if ( ret != next_result::option_short
- && ret != next_result::option_long)
- handle_invalid_arg(c);
-
- /* find option */
- auto it = _map.find(key);
- if (it == _map.end())
- {
- handle_invalid_arg(c);
- }
- else
- {
- it->second->parse(c);
- }
- }
- }
-
- void parser::print_help(std::ostream& os) const
- { printing { } (os, _group); }
-
- }
|