29#include "utils/wingetopt.h"
36const int no_argument = 0;
37const int required_argument = 1;
38const int optional_argument = 2;
46static char* optcursor = NULL;
57int getopt(
int argc,
char*
const argv[],
const char* optstring) {
59 const char* optdecl = NULL;
66 if (optind >= argc)
goto no_more_optchars;
70 if (argv[optind] == NULL)
goto no_more_optchars;
74 if (*argv[optind] !=
'-')
goto no_more_optchars;
78 if (strcmp(argv[optind],
"-") == 0)
goto no_more_optchars;
82 if (strcmp(argv[optind],
"--") == 0) {
84 goto no_more_optchars;
87 if (optcursor == NULL || *optcursor ==
'\0') optcursor = argv[optind] + 1;
98 optdecl = strchr(optstring, optchar);
102 if (optdecl[1] ==
':') {
103 optarg = ++optcursor;
104 if (*optarg ==
'\0') {
110 if (optdecl[2] !=
':') {
121 if (++optind < argc) {
122 optarg = argv[optind];
129 optchar = (optstring[0] ==
':') ?
':' :
'?';
144 if (optcursor == NULL || *++optcursor ==
'\0') ++optind;
157int getopt_long(
int argc,
char*
const argv[],
const char* optstring,
158 const struct option* longopts,
int* longindex) {
159 const struct option* o = longopts;
160 const struct option* match = NULL;
162 size_t argument_name_length = 0;
163 const char* current_argument = NULL;
169 if (optind >= argc)
return -1;
171 if (strlen(argv[optind]) < 3 || strncmp(argv[optind],
"--", 2) != 0)
172 return getopt(argc, argv, optstring);
175 current_argument = argv[optind] + 2;
176 argument_name_length = strcspn(current_argument,
"=");
177 for (; o->name; ++o) {
178 if (strncmp(o->name, current_argument, argument_name_length) == 0) {
184 if (num_matches == 1) {
187 if (longindex) *longindex = (match - longopts);
193 if (match->flag) *(match->flag) = match->val;
195 retval = match->flag ? 0 : match->val;
197 if (match->has_arg != no_argument) {
198 optarg = strchr(argv[optind],
'=');
199 if (optarg != NULL) ++optarg;
201 if (match->has_arg == required_argument) {
204 if (optarg == NULL && ++optind < argc) { optarg = argv[optind]; }
206 if (optarg == NULL) retval =
':';
208 }
else if (strchr(argv[optind],
'=')) {