* Functions the same as getopt_long. See `man 3 getopt_long`. */
| 95 | * Functions the same as getopt_long. See `man 3 getopt_long`. |
| 96 | */ |
| 97 | int |
| 98 | argparser::getopt(string* shortopts, const struct option* longopts, |
| 99 | int* /*longindex*/) |
| 100 | { |
| 101 | if (optind == argv.size()) |
| 102 | return -1; |
| 103 | |
| 104 | string arg; |
| 105 | arg = argv[optind]; |
| 106 | if (arg[0] != '-' || (arg[0] == '-' && arg.size() == 1)) |
| 107 | return -1; |
| 108 | optind++; |
| 109 | |
| 110 | int retval = '?'; |
| 111 | if (arg.compare(0, 2, "--") == 0) { |
| 112 | if (arg.size() == 2) return -1; // " -- " separates options and files |
| 113 | const struct option* opt = longopts; |
| 114 | while (opt->name != nullptr) { |
| 115 | if (arg.compare(2, string::npos, opt->name) == 0) { |
| 116 | retval = opt->val; |
| 117 | if (opt->has_arg != option::no_argument) { |
| 118 | if (optind >= argv.size() || (optarg = argv[optind++])[0] == '-') { |
| 119 | optarg.clear(); |
| 120 | optind--; |
| 121 | if (opt->has_arg == option::required_argument) |
| 122 | retval = ':'; |
| 123 | } |
| 124 | } |
| 125 | if (opt->flag != nullptr) { |
| 126 | *opt->flag = opt->val; |
| 127 | retval = 0; |
| 128 | } |
| 129 | break; |
| 130 | } |
| 131 | opt++; |
| 132 | } |
| 133 | } else if (shortopts != nullptr && arg.compare(0, 1, "-") == 0) { |
| 134 | size_t pos = shortopts->find(arg.substr(1, 1)); |
| 135 | if (pos != string::npos) { |
| 136 | retval = (*shortopts)[pos]; |
| 137 | if (pos < shortopts->length() |
| 138 | && ((*shortopts)[++pos] == ':' || (*shortopts)[pos] == ';')) { |
| 139 | if (optind >= argv.size() || (optarg = argv[optind++])[0] == '-') { |
| 140 | optarg.clear(); |
| 141 | optind--; |
| 142 | if ((*shortopts)[pos] == ':') // required argument |
| 143 | retval = ':'; |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | return retval; |
| 150 | } |
| 151 | |
| 152 | //================== Helper for apps' processArgs ======================== |
| 153 |
no test coverage detected