00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013 #include <sstream>
00014 #include "TypedOptionParser.h"
00015
00016 namespace optparse {
00017
00018 using namespace std;
00019
00020 void TypedOptionParser::add_option(Teuchos::ParameterList& params,
00021 std::string shrt_flag, std::string lng_flag,
00022 std::string destination, std::string help, action_t act,
00023 std::string allowed_values) {
00024
00025 string key(destination);
00026 Teuchos::ParameterList* sublist = ¶ms;
00027 size_t dot_pos;
00028 while((dot_pos = key.find('.')) != string::npos) {
00029 sublist = &sublist->sublist(key.substr(0, dot_pos));
00030 key = key.substr(dot_pos+1, string::npos);
00031 }
00032
00033 type_t type;
00034 ostringstream buf;
00035 if (sublist->isType<int>(key)) {
00036 type = INT;
00037 buf << sublist->get<int>(key);
00038 } else if (sublist->isType<double>(key)) {
00039 type = DOUBLE;
00040 buf << sublist->get<double>(key);
00041 } else if (sublist->isType<string>(key)) {
00042 type = STRING;
00043 buf << sublist->get<string>(key);
00044 } else if (sublist->isType<bool>(key)) {
00045 type = BOOL;
00046 if (sublist->get<bool>(key))
00047 buf << '1';
00048 else
00049 buf << '0';
00050 } else
00051 assert(false);
00052 string default_value = buf.str();
00053 OptionParser::add_option(shrt_flag, lng_flag, destination, help, act, type, default_value, allowed_values);
00054 }
00055
00056 void TypedOptionParser::set_parameter_list(Teuchos::ParameterList& params) {
00057 for (OptionParser::options_type::iterator it = options.begin(); it != options.end(); ++ it) {
00058
00059 string key(it->first);
00060 Teuchos::ParameterList* sublist = ¶ms;
00061 size_t dot_pos;
00062 while((dot_pos = key.find('.')) != string::npos) {
00063 sublist = &sublist->sublist(key.substr(0, dot_pos));
00064 key = key.substr(dot_pos+1, string::npos);
00065 }
00066
00067 string val(it->second);
00068 size_t colon_pos = val.find(':');
00069 assert(colon_pos != string::npos);
00070 string type(val.substr(colon_pos+1, string::npos));
00071 val = val.substr(0, colon_pos);
00072
00073 if (type == "STRING")
00074 sublist->set(key, val);
00075 else if (type == "DOUBLE")
00076 sublist->set(key, atof(val.c_str()));
00077 else if (type == "INT")
00078 sublist->set(key, atoi(val.c_str()));
00079 else if (type == "BOOL") {
00080 sublist->set(key, val != "0");
00081 } else
00082 assert(false);
00083 }
00084 }
00085
00086 string TypedOptionParser::get_option(std::string option_name) {
00087 string arg(options[option_name]);
00088 size_t colon_pos = arg.find(':');
00089 return arg.substr(0, colon_pos);
00090 }
00091
00092 void TypedOptionParser::set_option(Option& option, string argument) {
00093 if (option.is_allowed(argument))
00094 options[option.destination] = argument + ":" + type2string(option.type_);
00095 else
00096 throw OptionError(option.shrt_flag + " " + option.lng_flag, "Invalid argument for option");
00097 }
00098
00099 }