blob: 42abd991ae1c13ce3944b6ad41e3e18083eb0cd1 [file] [log] [blame]
Brad Bishop29dbfa62016-12-19 13:39:57 -05001/**
2 * Copyright © 2016 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 */
Patrick Williams3667cf32015-10-20 22:39:11 -050016#include <iostream>
17#include <iterator>
18#include <algorithm>
19#include <cassert>
Matthew Barth6292aee2016-10-06 10:15:48 -050020#include "argument.hpp"
Patrick Williams3667cf32015-10-20 22:39:11 -050021
22ArgumentParser::ArgumentParser(int argc, char** argv)
23{
24 int option = 0;
Brad Bishop6bb97a92016-12-19 13:06:40 -050025 while (-1 != (option = getopt_long(argc, argv, optionstr, options, NULL)))
Patrick Williams3667cf32015-10-20 22:39:11 -050026 {
27 if ((option == '?') || (option == 'h'))
28 {
29 usage(argv);
30 exit(-1);
31 }
32
33 auto i = &options[0];
Brad Bishop6bb97a92016-12-19 13:06:40 -050034 while ((i->val != option) && (i->val != 0))
35 {
36 ++i;
37 }
Patrick Williams3667cf32015-10-20 22:39:11 -050038
39 if (i->val)
Brad Bishop6bb97a92016-12-19 13:06:40 -050040 {
Patrick Williams3667cf32015-10-20 22:39:11 -050041 arguments[i->name] = (i->has_arg ? optarg : true_string);
Brad Bishop6bb97a92016-12-19 13:06:40 -050042 }
Patrick Williams3667cf32015-10-20 22:39:11 -050043 }
44}
45
46const std::string& ArgumentParser::operator[](const std::string& opt)
47{
48 auto i = arguments.find(opt);
49 if (i == arguments.end())
50 {
51 return empty_string;
52 }
53 else
54 {
55 return i->second;
56 }
57}
58
59void ArgumentParser::usage(char** argv)
60{
61 std::cerr << "Usage: " << argv[0] << " [options]" << std::endl;
62 std::cerr << "Options:" << std::endl;
Adriana Kobylakf261fa02016-06-12 15:45:42 -050063 std::cerr << " --help print this menu" << std::endl;
Patrick Williams3667cf32015-10-20 22:39:11 -050064 std::cerr << " --path=<path> sysfs location to monitor"
65 << std::endl;
66}
67
68const option ArgumentParser::options[] =
69{
70 { "path", required_argument, NULL, 'p' },
71 { "help", no_argument, NULL, 'h' },
72 { 0, 0, 0, 0},
73};
74
75const char* ArgumentParser::optionstr = "p:?h";
76
77const std::string ArgumentParser::true_string = "true";
78const std::string ArgumentParser::empty_string = "";