blob: 222b7d38ced8e7340e46c7f681a714ab65159d19 [file] [log] [blame]
Matt Spinlere3b859c2017-05-25 11:15:43 -05001/**
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 <iostream>
17#include <iterator>
18#include <algorithm>
19#include "argument.hpp"
20
21namespace phosphor
22{
23namespace gpio
24{
25
26ArgumentParser::ArgumentParser(int argc, char** argv)
27{
28 int option = 0;
29 while (-1 != (option = getopt_long(argc, argv, optionStr, options, NULL)))
30 {
31 if ((option == '?') || (option == 'h'))
32 {
33 usage(argv);
34 exit(-1);
35 }
36
37 auto i = &options[0];
38 while ((i->val != option) && (i->val != 0))
39 {
40 ++i;
41 }
42
43 if (i->val)
44 {
45 arguments[i->name] = (i->has_arg ? optarg : trueString);
46 }
47 }
48}
49
50const std::string& ArgumentParser::operator[](const std::string& opt)
51{
52 auto i = arguments.find(opt);
53 if (i == arguments.end())
54 {
55 return emptyString;
56 }
57 else
58 {
59 return i->second;
60 }
61}
62
63void ArgumentParser::usage(char** argv)
64{
65 std::cerr << "Usage: " << argv[0] << " [options]\n";
66 std::cerr << "Options:\n";
67 std::cerr << " --help Print this menu.\n";
68 std::cerr << " --gpio=<gpio> The GPIO number. Example: 1\n";
69 std::cerr << " --path=<path> The path to the GPIO device."
70 " Example: /dev/gpiochip0\n";
71 std::cerr << " --delay=<delay> The delay in ms in between a toggle."
72 " Example: 5\n";
73 std::cerr << " --action=<action> The action to do.\n";
74 std::cerr << " Valid actions: low, high, low_high, "
75 "high_low\n";
76 std::cerr << std::flush;
77}
78
79const option ArgumentParser::options[] =
80{
81 { "action", required_argument, NULL, 'a' },
82 { "gpio", required_argument, NULL, 'g' },
83 { "delay", required_argument, NULL, 'd' },
84 { "path", required_argument, NULL, 'p' },
85 { "help", no_argument, NULL, 'h' },
86 { 0, 0, 0, 0},
87};
88
89const char* ArgumentParser::optionStr = "a:g:d:p:h?";
90
91const std::string ArgumentParser::trueString = "true";
92const std::string ArgumentParser::emptyString = "";
93
94}
95}