| 850 | // |
| 851 | |
| 852 | static bool common_params_parse_ex(int argc, char ** argv, common_params_context & ctx_arg) { |
| 853 | std::string arg; |
| 854 | const std::string arg_prefix = "--"; |
| 855 | common_params & params = ctx_arg.params; |
| 856 | |
| 857 | std::unordered_map<std::string, common_arg *> arg_to_options; |
| 858 | for (auto & opt : ctx_arg.options) { |
| 859 | for (const auto & arg : opt.args) { |
| 860 | arg_to_options[arg] = &opt; |
| 861 | } |
| 862 | } |
| 863 | |
| 864 | // handle environment variables |
| 865 | for (auto & opt : ctx_arg.options) { |
| 866 | std::string value; |
| 867 | if (opt.get_value_from_env(value)) { |
| 868 | try { |
| 869 | if (opt.handler_void && (value == "1" || value == "true")) { |
| 870 | opt.handler_void(params); |
| 871 | } |
| 872 | if (opt.handler_int) { |
| 873 | opt.handler_int(params, std::stoi(value)); |
| 874 | } |
| 875 | if (opt.handler_string) { |
| 876 | opt.handler_string(params, value); |
| 877 | continue; |
| 878 | } |
| 879 | } catch (std::exception & e) { |
| 880 | throw std::invalid_argument(string_format( |
| 881 | "error while handling environment variable \"%s\": %s\n\n", opt.env, e.what())); |
| 882 | } |
| 883 | } |
| 884 | } |
| 885 | |
| 886 | // handle command line arguments |
| 887 | auto check_arg = [&](int i) { |
| 888 | if (i+1 >= argc) { |
| 889 | throw std::invalid_argument("expected value for argument"); |
| 890 | } |
| 891 | }; |
| 892 | |
| 893 | for (int i = 1; i < argc; i++) { |
| 894 | const std::string arg_prefix = "--"; |
| 895 | |
| 896 | std::string arg = argv[i]; |
| 897 | if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) { |
| 898 | std::replace(arg.begin(), arg.end(), '_', '-'); |
| 899 | } |
| 900 | if (arg_to_options.find(arg) == arg_to_options.end()) { |
| 901 | throw std::invalid_argument(string_format("error: invalid argument: %s", arg.c_str())); |
| 902 | } |
| 903 | auto opt = *arg_to_options[arg]; |
| 904 | if (opt.has_value_from_env()) { |
| 905 | fprintf(stderr, "warn: %s environment variable is set, but will be overwritten by command line argument %s\n", opt.env, arg.c_str()); |
| 906 | } |
| 907 | try { |
| 908 | if (opt.handler_void) { |
| 909 | opt.handler_void(params); |
no test coverage detected