blob: 3df84e7217361778a02c4ef98ddaef4f2eda2de4 [file] [log] [blame]
Vishwanatha Subbanna835571e2016-11-30 11:29:30 +05301/**
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 */
16
17#include <iostream>
18#include <iterator>
19#include <algorithm>
20#include <cassert>
21#include "argument.hpp"
22
23namespace phosphor
24{
25namespace led
26{
27
28const std::string ArgumentParser::true_string = "true";
29const std::string ArgumentParser::empty_string = "";
30
31const char* ArgumentParser::optionstr = "n:p:?h";
32const option ArgumentParser::options[] =
33{
34 { "name", required_argument, nullptr, 'n' },
35 { "path", required_argument, nullptr, 'p' },
36 { "help", no_argument, nullptr, 'h' },
37 { 0, 0, 0, 0},
38};
39
40ArgumentParser::ArgumentParser(int argc, char** argv)
41{
42 int option = 0;
43 while(-1 != (option = getopt_long(argc, argv, optionstr, options, nullptr)))
44 {
45 if ((option == '?') || (option == 'h'))
46 {
47 usage(argv);
48 exit(-1);
49 }
50
51 auto i = &options[0];
52 while ((i->val != option) && (i->val != 0)) ++i;
53
54 if (i->val)
55 arguments[i->name] = (i->has_arg ? optarg : true_string);
56 }
57}
58
59const std::string& ArgumentParser::operator[](const std::string& opt)
60{
61 auto i = arguments.find(opt);
62 if (i == arguments.end())
63 {
64 return empty_string;
65 }
66 else
67 {
68 return i->second;
69 }
70}
71
72void ArgumentParser::usage(char** argv)
73{
74 std::cerr << "Usage: " << argv[0] << " [options]" << std::endl;
75 std::cerr << "Options:" << std::endl;
76 std::cerr << " --help Print this menu" << std::endl;
77 std::cerr << " --name=<name> Name of the LED"
78 << std::endl;
79 std::cerr << " --path=<path> sysfs path like /sys/class/leds"
80 << std::endl;
81}
82} // namespace led
83} // namespace phosphor