1 /* Copyright (c) 2014, Google Inc. 2 * 3 * Permission to use, copy, modify, and/or distribute this software for any 4 * purpose with or without fee is hereby granted, provided that the above 5 * copyright notice and this permission notice appear in all copies. 6 * 7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION 12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ 14 15 #include <string> 16 #include <vector> 17 #include <map> 18 19 #include <string.h> 20 21 #include "internal.h" 22 23 24 bool ParseKeyValueArguments(std::map<std::string, std::string> *out_args, 25 const std::vector<std::string> &args, 26 const struct argument *templates) { 27 out_args->clear(); 28 29 for (size_t i = 0; i < args.size(); i++) { 30 const std::string &arg = args[i]; 31 const struct argument *templ = nullptr; 32 for (size_t j = 0; templates[j].name[0] != 0; j++) { 33 if (strcmp(arg.c_str(), templates[j].name) == 0) { 34 templ = &templates[j]; 35 break; 36 } 37 } 38 39 if (templ == nullptr) { 40 fprintf(stderr, "Unknown argument: %s\n", arg.c_str()); 41 return false; 42 } 43 44 if (i + 1 >= args.size()) { 45 fprintf(stderr, "Missing argument for option: %s\n", arg.c_str()); 46 return false; 47 } 48 49 if (out_args->find(arg) != out_args->end()) { 50 fprintf(stderr, "Duplicate value given for: %s\n", arg.c_str()); 51 return false; 52 } 53 54 (*out_args)[arg] = args[++i]; 55 } 56 57 for (size_t j = 0; templates[j].name[0] != 0; j++) { 58 const struct argument *templ = &templates[j]; 59 if (templ->required && out_args->find(templ->name) == out_args->end()) { 60 fprintf(stderr, "Missing value for required argument: %s\n", templ->name); 61 return false; 62 } 63 } 64 65 return true; 66 } 67 68 void PrintUsage(const struct argument *templates) { 69 for (size_t i = 0; templates[i].name[0] != 0; i++) { 70 const struct argument *templ = &templates[i]; 71 fprintf(stderr, "%s\t%s\n", templ->name, templ->description); 72 } 73 } 74