blob: 6cbfab656354471b0a382a2803cf77ce324185a3 [file] [log] [blame]
Adam Langleyaacec172014-06-20 12:00:00 -07001/* 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
Ben Laurieeba23842014-09-30 12:44:15 +010019#include <stdio.h>
Adam Langleyaacec172014-06-20 12:00:00 -070020#include <string.h>
21
22#include "internal.h"
23
24
25bool ParseKeyValueArguments(std::map<std::string, std::string> *out_args,
26 const std::vector<std::string> &args,
27 const struct argument *templates) {
28 out_args->clear();
29
30 for (size_t i = 0; i < args.size(); i++) {
31 const std::string &arg = args[i];
32 const struct argument *templ = nullptr;
33 for (size_t j = 0; templates[j].name[0] != 0; j++) {
34 if (strcmp(arg.c_str(), templates[j].name) == 0) {
35 templ = &templates[j];
36 break;
37 }
38 }
39
40 if (templ == nullptr) {
41 fprintf(stderr, "Unknown argument: %s\n", arg.c_str());
42 return false;
43 }
44
45 if (i + 1 >= args.size()) {
46 fprintf(stderr, "Missing argument for option: %s\n", arg.c_str());
47 return false;
48 }
49
50 if (out_args->find(arg) != out_args->end()) {
51 fprintf(stderr, "Duplicate value given for: %s\n", arg.c_str());
52 return false;
53 }
54
55 (*out_args)[arg] = args[++i];
56 }
57
58 for (size_t j = 0; templates[j].name[0] != 0; j++) {
59 const struct argument *templ = &templates[j];
60 if (templ->required && out_args->find(templ->name) == out_args->end()) {
61 fprintf(stderr, "Missing value for required argument: %s\n", templ->name);
62 return false;
63 }
64 }
65
66 return true;
67}
68
69void PrintUsage(const struct argument *templates) {
70 for (size_t i = 0; templates[i].name[0] != 0; i++) {
71 const struct argument *templ = &templates[i];
72 fprintf(stderr, "%s\t%s\n", templ->name, templ->description);
73 }
74}