Imported Upstream version 0.7.8
[platform/upstream/libsolv.git] / win32 / getopt.c
1 #include <unistd.h>
2 #include <wchar.h>
3 #include <string.h>
4 #include <limits.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7
8 char *optarg;
9 int optind=1, opterr=1, optopt, __optpos, __optreset=0;
10
11 #define optpos __optpos
12
13 void __getopt_msg(const char *a, const char *b, const char *c, size_t l)
14 {
15         FILE *f = stderr;
16         fputs(a, f)>=0
17         && fwrite(b, strlen(b), 1, f)
18         && fwrite(c, 1, l, f)==l
19         && putc('\n', f);
20 }
21
22 int getopt(int argc, char * const argv[], const char *optstring)
23 {
24         int i;
25         wchar_t c, d;
26         int k, l;
27         char *optchar;
28
29         if (!optind || __optreset) {
30                 __optreset = 0;
31                 __optpos = 0;
32                 optind = 1;
33         }
34
35         if (optind >= argc || !argv[optind])
36                 return -1;
37
38         if (argv[optind][0] != '-') {
39                 if (optstring[0] == '-') {
40                         optarg = argv[optind++];
41                         return 1;
42                 }
43                 return -1;
44         }
45
46         if (!argv[optind][1])
47                 return -1;
48
49         if (argv[optind][1] == '-' && !argv[optind][2])
50                 return optind++, -1;
51
52         if (!optpos) optpos++;
53         if ((k = mbtowc(&c, argv[optind]+optpos, MB_LEN_MAX)) < 0) {
54                 k = 1;
55                 c = 0xfffd; /* replacement char */
56         }
57         optchar = argv[optind]+optpos;
58         optpos += k;
59
60         if (!argv[optind][optpos]) {
61                 optind++;
62                 optpos = 0;
63         }
64
65         if (optstring[0] == '-' || optstring[0] == '+')
66                 optstring++;
67
68         i = 0;
69         d = 0;
70         do {
71                 l = mbtowc(&d, optstring+i, MB_LEN_MAX);
72                 if (l>0) i+=l; else i++;
73         } while (l && d != c);
74
75         if (d != c || c == ':') {
76                 optopt = c;
77                 if (optstring[0] != ':' && opterr)
78                         __getopt_msg(argv[0], ": unrecognized option: ", optchar, k);
79                 return '?';
80         }
81         if (optstring[i] == ':') {
82                 optarg = 0;
83                 if (optstring[i+1] != ':' || optpos) {
84                         optarg = argv[optind++] + optpos;
85                         optpos = 0;
86                 }
87                 if (optind > argc) {
88                         optopt = c;
89                         if (optstring[0] == ':') return ':';
90                         if (opterr) __getopt_msg(argv[0],
91                                 ": option requires an argument: ",
92                                 optchar, k);
93                         return '?';
94                 }
95         }
96         return c;
97 }