1 /**
2 * Copyright © 2017 IBM Corporation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #include "argument.hpp"
17
18 #include <algorithm>
19 #include <iostream>
20 #include <iterator>
21
22 namespace witherspoon
23 {
24 namespace power
25 {
26
usage(char ** argv)27 void ArgumentParser::usage(char** argv)
28 {
29 std::cerr << "Usage: " << argv[0] << " [options]\n";
30 std::cerr << "Options:\n";
31 std::cerr << " --help Print this menu\n";
32 std::cerr << " --action=<action> Action: pgood-monitor "
33 "or runtime-monitor\n";
34 std::cerr << " --interval=<interval> Interval in milliseconds:\n";
35 std::cerr << " PGOOD monitor: time allowed for PGOOD to come up\n";
36 std::cerr << " Runtime monitor: polling interval.\n";
37
38 std::cerr << std::flush;
39 }
40
41 const option ArgumentParser::options[] = {
42 {"action", required_argument, NULL, 'a'},
43 {"interval", required_argument, NULL, 'i'},
44 {"help", no_argument, NULL, 'h'},
45 {0, 0, 0, 0},
46 };
47
48 const char* ArgumentParser::optionStr = "a:i:h?";
ArgumentParser(int argc,char ** argv)49 ArgumentParser::ArgumentParser(int argc, char** argv)
50 {
51 int option = 0;
52 while (-1 != (option = getopt_long(argc, argv, optionStr, options, NULL)))
53 {
54 if ((option == '?') || (option == 'h'))
55 {
56 usage(argv);
57 exit(-1);
58 }
59
60 auto i = &options[0];
61 while ((i->val != option) && (i->val != 0))
62 {
63 ++i;
64 }
65
66 if (i->val)
67 {
68 arguments[i->name] = (i->has_arg ? optarg : trueString);
69 }
70 }
71 }
72
operator [](const std::string & opt)73 const std::string& ArgumentParser::operator[](const std::string& opt)
74 {
75 auto i = arguments.find(opt);
76 if (i == arguments.end())
77 {
78 return emptyString;
79 }
80 else
81 {
82 return i->second;
83 }
84 }
85
86 const std::string ArgumentParser::trueString = "true";
87 const std::string ArgumentParser::emptyString = "";
88
89 } // namespace power
90 } // namespace witherspoon
91