1 /** 2 * Copyright © 2018 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 phosphor 23 { 24 namespace certs 25 { 26 namespace util 27 { 28 29 ArgumentParser::ArgumentParser(int argc, char** argv) 30 { 31 auto option = 0; 32 while (-1 != (option = getopt_long(argc, argv, optionstr, options, NULL))) 33 { 34 if ((option == '?') || (option == 'h')) 35 { 36 usage(argv); 37 exit(-1); 38 } 39 40 auto i = &options[0]; 41 while ((i->val != option) && (i->val != 0)) 42 { 43 ++i; 44 } 45 46 if (i->val) 47 { 48 arguments[i->name] = (i->has_arg ? optarg : true_string); 49 } 50 } 51 } 52 53 const std::string& ArgumentParser::operator[](const std::string& opt) 54 { 55 auto i = arguments.find(opt); 56 if (i == arguments.end()) 57 { 58 return empty_string; 59 } 60 else 61 { 62 return i->second; 63 } 64 } 65 66 void ArgumentParser::usage(char** argv) 67 { 68 std::cerr << "Usage: " << argv[0] << " [options]\n"; 69 std::cerr << "Options:\n"; 70 std::cerr << " --help Print this menu\n"; 71 std::cerr << " --type certificate type\n"; 72 std::cerr << " Valid types: client,server,authority\n"; 73 std::cerr << " --endpoint d-bus endpoint\n"; 74 std::cerr << " --path certificate file path\n"; 75 std::cerr << " --unit=<name> Optional systemd unit need to reload\n"; 76 std::cerr << std::flush; 77 } 78 79 const option ArgumentParser::options[] = { 80 {"type", required_argument, nullptr, 't'}, 81 {"endpoint", required_argument, nullptr, 'e'}, 82 {"path", required_argument, nullptr, 'p'}, 83 {"unit", optional_argument, nullptr, 'u'}, 84 {"help", no_argument, nullptr, 'h'}, 85 {0, 0, 0, 0}, 86 }; 87 88 const char* ArgumentParser::optionstr = "tepuh?"; 89 90 const std::string ArgumentParser::true_string = "true"; 91 const std::string ArgumentParser::empty_string = ""; 92 93 } // namespace util 94 } // namespace certs 95 } // namespace phosphor 96