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
18 #include <stdio.h>
19 #include <string.h>
20
21 #include "internal.h"
22
23
ParseKeyValueArguments(std::map<std::string,std::string> * out_args,const std::vector<std::string> & args,const struct argument * templates)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 (out_args->find(arg) != out_args->end()) {
45 fprintf(stderr, "Duplicate argument: %s\n", arg.c_str());
46 return false;
47 }
48
49 if (templ->type == kBooleanArgument) {
50 (*out_args)[arg] = "";
51 } else {
52 if (i + 1 >= args.size()) {
53 fprintf(stderr, "Missing argument for option: %s\n", arg.c_str());
54 return false;
55 }
56 (*out_args)[arg] = args[++i];
57 }
58 }
59
60 for (size_t j = 0; templates[j].name[0] != 0; j++) {
61 const struct argument *templ = &templates[j];
62 if (templ->type == kRequiredArgument &&
63 out_args->find(templ->name) == out_args->end()) {
64 fprintf(stderr, "Missing value for required argument: %s\n", templ->name);
65 return false;
66 }
67 }
68
69 return true;
70 }
71
PrintUsage(const struct argument * templates)72 void PrintUsage(const struct argument *templates) {
73 for (size_t i = 0; templates[i].name[0] != 0; i++) {
74 const struct argument *templ = &templates[i];
75 fprintf(stderr, "%s\t%s\n", templ->name, templ->description);
76 }
77 }
78