blob: 570c97f397bc0becd8edcc272bfc94afa72022e1 [file] [log] [blame]
Lei YU0bf1b782019-08-29 16:02:30 +08001/**
2 * Copyright © 2019 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
22namespace phosphor
23{
24namespace power
25{
26
27void ArgumentParser::usage(char** argv)
28{
29 std::cerr << "Usage: " << argv[0] << " [options] <psu-inventory-path>\n";
30 std::cerr << "Options:\n";
31 std::cerr << " --help Print this menu\n";
32 std::cerr << " --get-version Get PSU version\n";
33 std::cerr << std::flush;
34}
35
36const option ArgumentParser::options[] = {
37 {"get-version", required_argument, NULL, 'g'},
38 {"help", no_argument, NULL, 'h'},
39 {0, 0, 0, 0},
40};
41
42const char* ArgumentParser::optionStr = "g:h?";
43ArgumentParser::ArgumentParser(int argc, char** argv)
44{
45 int option = 0;
46 while (-1 != (option = getopt_long(argc, argv, optionStr, options, NULL)))
47 {
48 if ((option == '?') || (option == 'h'))
49 {
50 usage(argv);
51 exit(-1);
52 }
53
54 auto i = &options[0];
55 while ((i->val != option) && (i->val != 0))
56 {
57 ++i;
58 }
59
60 if (i->val)
61 {
62 arguments[i->name] = (i->has_arg ? optarg : trueString);
63 }
64 }
65}
66
67const std::string& ArgumentParser::operator[](const std::string& opt)
68{
69 auto i = arguments.find(opt);
70 if (i == arguments.end())
71 {
72 return emptyString;
73 }
74 else
75 {
76 return i->second;
77 }
78}
79
80const std::string ArgumentParser::trueString = "true";
81const std::string ArgumentParser::emptyString = "";
82
83} // namespace power
84} // namespace phosphor