6#include <kernel/util/arg_parser.hpp>
22 if(!custom_name.empty())
26 if(!long_flag.empty())
28 return long_flag.substr(2);
31 if(!short_flag.empty())
33 return short_flag.substr(1);
36 if(!property_path.empty())
41 if(!environment_variable.empty())
43 return environment_variable;
52 if(priority < incoming_priority)
57 arguments.push_back(s.
trim());
58 priority = incoming_priority;
60 else if(priority == incoming_priority)
64 arguments.push_back(s.
trim());
70 if(required && !set_by_user)
72 errors.push_back(
"Error: Parameter " +
name() +
" not given, but is required!");
82 catch(std::bad_any_cast& e)
86 catch(std::invalid_argument& e)
88 errors.push_back(
"Error: Validation of parameter " +
name() +
" failed with message: " + e.what());
92 for(
const auto& [core, condition] : needs)
96 XABORTM(
"Expired weak ptr to parameter core of " +
name());
99 auto ptr = core.lock();
101 if(set_by_user && condition(value))
103 if(!ptr->set_by_user)
106 "Error: Parameter " +
name() +
" needs parameter " + ptr->name() +
", but parameter " + ptr->name() +
107 " was not set by user");
115 if(arguments.empty())
128 if(type == ParameterType::collection_option)
130 String merged = std::accumulate(
134 [](
const String& a,
const String& b) {
return a +
" " + b; });
138 arguments.push_back(merged.
trim());
141 if(arguments.size() > 1)
143 errors.push_back(
"Error: Parameter " +
name() +
" was set multiple times. Only the first value is considered!");
149 "Error: No parser for parameter " +
name() +
150 ". Ensure operator>> is available for your type or set a custom parser!");
156 parser(value, arguments.front());
158 catch(std::bad_any_cast& e)
162 catch(std::invalid_argument& e)
164 errors.push_back(
"Error: Parsing for parameter " +
name() +
" failed with message: " + e.what());
170 if(!set_by_user && deriver)
173 std::deque<std::reference_wrapper<std::any>> args;
175 for(
const auto& core : derives_from)
179 XABORTM(
"Expired weak ptr to parameter core of " +
name());
182 auto ptr = core.lock();
184 args.emplace_back(ptr->value);
188 deriver(value, args);
194 for(
auto& [core, condition] : hide_if)
200 XABORTM(
"Expired weak ptr to parameter core of " +
name());
203 auto ptr = core.lock();
216 value = default_value;
227 std::stringstream stream;
233 stream <<
"Usage: " <<
_program <<
" [OPTIONS]\n\n";
234 stream <<
"Options:\n";
236 for(
const auto& core : _parameters)
246 std::stringstream stream;
249 String::size_type name_padding(0);
250 for(
const auto& core : _parameters)
252 name_padding = std::max(name_padding, core->name().size());
256 const String::size_type source_padding(10);
257 const String::size_type header_width(75);
267 for(
const auto& core : _parameters)
275 XASSERT(core->value.has_value());
277 stream << core->name().pad_back(name_padding,
'.');
280 switch(core->priority)
282 case priority_default: stream <<
"default |";
break;
283 case priority_env: stream <<
"env |";
break;
284 case priority_property: stream <<
"property |";
break;
285 case priority_cli: stream <<
"cli |";
break;
286 default: stream <<
" |";
289 if(core->type == Intern::ParameterType::flag)
291 stream << (std::any_cast<const bool&>(core->value) ?
"true" :
"false");
296 core->printer(stream, core->value);
311 for(
auto& core : _parameters)
320 _collect_args(argc, argv);
324 for(
auto& core : _parameters)
328 core->parse(_errors);
330 for(
const String& path : std::any_cast<std::deque<String>>(core->value))
334 pmap.
merge(tmp_map,
true);
340 for(
auto& core : _parameters)
345 return _errors.empty();
359 for(
auto& core : _parameters)
368 if(property_map !=
nullptr)
370 _collect_property_map(property_map);
374 _collect_args(argc, argv);
377 for(
auto& core : _parameters)
379 core->parse(_errors);
395 [](
auto& a,
auto& b) { return a->name().compare_no_case(b->name()) < 0; });
397 return _errors.empty();
406 std::stringstream ss;
407 core.printer(ss, core.default_value);
418 std::stringstream ss;
419 core.printer(ss, core.value);
426 std::set<String> short_flags;
427 std::set<String> long_flags;
428 std::set<String> environment_variables;
429 std::set<String> property_paths;
433 auto handle_flag = [&](std::set<String>& set,
const String& s)
440 if(set.find(s) != set.end())
442 _errors.push_back(
"Error: Flag " + s +
" is used by multiple parameters");
451 for(
auto& core : _parameters)
453 handle_flag(short_flags, core->short_flag);
454 handle_flag(long_flags, core->long_flag);
455 handle_flag(environment_variables, core->environment_variable);
456 handle_flag(property_paths, core->property_path);
462 void ArgParser::_collect_env()
464 for(
auto& core : _parameters)
466 const char*
value = std::getenv(core->environment_variable.c_str());
470 core->add_argument(s, priority_env);
475 void ArgParser::_collect_property_map(
const PropertyMap* property_map)
477 for(
auto& core : _parameters)
479 auto [string,
success] = property_map->query(core->property_path);
482 core->add_argument(
string, priority_property);
487 void ArgParser::_collect_args(
int argc,
const char*
const* argv)
496 std::deque<String> args;
498 for(
int i(1); i < argc; i++)
500 args.emplace_back(argv[i]);
504 while(idx < args.size())
506 const String& flag = args[idx++];
513 bool handled =
false;
514 for(
auto& core : _parameters)
516 if(flag.compare_no_case(core->short_flag) != 0 && flag.compare_no_case(core->long_flag) != 0)
523 if(core->type == Intern::ParameterType::flag)
525 if(std::any_cast<const bool&>(core->default_value))
527 core->add_argument(
"false", priority_cli);
531 core->add_argument(
"true", priority_cli);
534 else if(core->type == Intern::ParameterType::option)
537 core->add_argument(args[idx++], priority_cli);
539 else if(core->type == Intern::ParameterType::collection_option)
542 while(idx < args.size() && !is_flag(args[idx]))
544 core->add_argument(args[idx++], priority_cli);
554 _errors.push_back(
"Error: Unknown flag " + flag);
558 while(idx < args.size() && !is_flag(args[idx]))
568 for(
auto& core : _parameters)
570 if(core->property_path.empty())
576 const auto path_components = core->property_path.split_by_charset(
"/");
579 for(
Index i(0); i < path_components.size() - 1; i++)
582 if(subsection ==
nullptr)
584 section = section->
add_section(path_components[i]);
588 section = subsection;
593 section->
add_entry(path_components.back(), extractor(*core));
600 core.short_flag.empty() && core.long_flag.empty() && core.property_path.empty() &&
601 core.environment_variable.empty())
608 auto format_flag = [&s](Intern::ParameterType type,
const String& flag,
const String& placeholder)
610 if(type == Intern::ParameterType::flag)
614 if(type == Intern::ParameterType::option)
616 s << flag <<
" <" << placeholder <<
">";
618 if(type == Intern::ParameterType::collection_option)
620 s << flag <<
" <" << placeholder <<
"s...>";
624 auto format_other = [&s](
const std::string_view prefix,
const String&
value)
625 { s <<
"[" << prefix <<
":" <<
value <<
"]"; };
629 bool has_prev =
false;
630 if(!core.short_flag.empty())
632 format_flag(core.type, core.short_flag, core.placeholder);
636 if(!core.long_flag.empty())
643 format_flag(core.type, core.long_flag, core.placeholder);
648 if(!core.property_path.empty())
655 format_other(
"property", core.property_path);
660 if(!core.environment_variable.empty())
667 format_other(
"env", core.environment_variable);
679 s <<
"\t\tRequired argument.\n";
684 s <<
"\t\t" << line.trim() <<
"\n";
#define XABORTM(msg)
Abortion macro definition with custom message.
#define XASSERT(expr)
Assertion macro definition.
static void parameter_help(const Intern::ParameterCore &core, std::stringstream &s)
Write flags, property path, environment variable and help text for given parameter to stringstream.
void _derive()
Derive parameters from other parameters.
void _hide()
Hide parameters if requested.
bool _allow_unknown_cli_flags
If true, unknown CLI flags do not produce errors.
void _validate()
Validate parameters after parsing.
String display() const
Produce formatted output of all values in this parser.
bool parse(int argc, const char *const *argv, const PropertyMap *property_map=nullptr)
Populate this parser.
void _property_map(PropertyMap &pmap, const std::function< String(const Intern::ParameterCore &)> &extractor)
Create a PropertyMap from all property-parameters using the given extractor.
void add_values_to_property_map(PropertyMap &pmap)
Adds the values of all property-parameters to the given PropertyMap.
void add_defaults_to_property_map(PropertyMap &pmap)
Adds the default values of all property-parameters to the given PropertyMap.
bool _check_for_unique_parameters()
bool bootstrap(int argc, const char *const *argv, PropertyMap &pmap)
Load PropertyMaps based on command line parameters or environment variables.
String _program
Path to program, i.e. argv[0].
String _description
Description of this parser. Displayed in help text.
String help_text() const
Generate help text for this parser.
Type-erased core of a Parameter.
String name() const
Tries to create a user-readable name for this parameter.
void parse(std::deque< String > &errors)
Parse this parameter.
void hide()
Hides other parameters based on this parameters hide_if declarations.
void derive_self()
Sets this parameters value based on other parameters.
void validate(std::deque< String > &errors) const
Validate this parameter.
void reset()
Reset this parameter to default.
void add_argument(const String &s, int incoming_priority)
Add an argument to this parameter.
A class organizing a tree of key-value pairs.
PropertyMap * add_section(String name)
Adds a new sub-section to this map.
PropertyMap * get_sub_section(String name)
Retrieves a sub-section by its name.
bool add_entry(String key, String value, bool replace=true)
Adds a new key-value pair to this map.
void merge(const PropertyMap §ion, bool replace=true)
Merges another PropertyMap into this.
void read(String filename, bool replace=true)
Parses a file in INI-format.
String class implementation.
String pad_back(size_type len, char c=' ') const
Pads the back of the string up to a desired length.
std::deque< String > split_by_charset(const String &charset) const
Splits the string by a delimiter charset.
String trim(const String &charset) const
Trims the string.
@ success
solving successful (convergence criterion fulfilled)
String stringify(const T_ &item)
Converts an item into a String.
@ value
specifies whether the space should supply basis function values
std::uint64_t Index
Index data type.