]> git.ozlabs.org Git - ccan/blob - ccan/opt/opt.c
opt: remove unused debug function and code, test a few more corner cases.
[ccan] / ccan / opt / opt.c
1 #include <ccan/opt/opt.h>
2 #include <string.h>
3 #include <errno.h>
4 #include <getopt.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <err.h>
8 #include <assert.h>
9 #include <stdarg.h>
10 #include <stdint.h>
11 #include "private.h"
12
13 struct opt_table *opt_table;
14 unsigned int opt_count, opt_num_short, opt_num_short_arg, opt_num_long;
15 const char *opt_argv0;
16
17 /* Returns string after first '-'. */
18 static const char *first_name(const char *names, unsigned *len)
19 {
20         *len = strcspn(names + 1, "/");
21         return names + 1;
22 }
23
24 static const char *next_name(const char *names, unsigned *len)
25 {
26         names += *len;
27         if (!names[0])
28                 return NULL;
29         return first_name(names + 1, len);
30 }
31
32 static const char *first_opt(unsigned *i, unsigned *len)
33 {
34         for (*i = 0; *i < opt_count; (*i)++) {
35                 if (opt_table[*i].flags == OPT_SUBTABLE)
36                         continue;
37                 return first_name(opt_table[*i].names, len);
38         }
39         return NULL;
40 }
41
42 static const char *next_opt(const char *p, unsigned *i, unsigned *len)
43 {
44         for (; *i < opt_count; (*i)++) {
45                 if (opt_table[*i].flags == OPT_SUBTABLE)
46                         continue;
47                 if (!p)
48                         return first_name(opt_table[*i].names, len);
49                 p = next_name(p, len);
50                 if (p)
51                         return p;
52         }
53         return NULL;
54 }
55
56 static const char *first_lopt(unsigned *i, unsigned *len)
57 {
58         const char *p;
59         for (p = first_opt(i, len); p; p = next_opt(p, i, len)) {
60                 if (p[0] == '-') {
61                         /* Skip leading "-" */
62                         (*len)--;
63                         p++;
64                         break;
65                 }
66         }
67         return p;
68 }
69
70 static const char *next_lopt(const char *p, unsigned *i, unsigned *len)
71 {
72         for (p = next_opt(p, i, len); p; p = next_opt(p, i, len)) {
73                 if (p[0] == '-') {
74                         /* Skip leading "-" */
75                         (*len)--;
76                         p++;
77                         break;
78                 }
79         }
80         return p;
81 }
82
83 const char *first_sopt(unsigned *i)
84 {
85         const char *p;
86         unsigned int len;
87
88         for (p = first_opt(i, &len); p; p = next_opt(p, i, &len)) {
89                 if (p[0] != '-')
90                         break;
91         }
92         return p;
93 }
94
95 const char *next_sopt(const char *p, unsigned *i)
96 {
97         unsigned int len = 1;
98         for (p = next_opt(p, i, &len); p; p = next_opt(p, i, &len)) {
99                 if (p[0] != '-')
100                         break;
101         }
102         return p;
103 }
104
105 static void check_opt(const struct opt_table *entry)
106 {
107         const char *p;
108         unsigned len;
109
110         assert(entry->flags == OPT_HASARG || entry->flags == OPT_NOARG);
111
112         assert(entry->names[0] == '-');
113         for (p = first_name(entry->names, &len); p; p = next_name(p, &len)) {
114                 if (*p == '-') {
115                         assert(len > 1);
116                         opt_num_long++;
117                 } else {
118                         assert(len == 1);
119                         assert(*p != ':');
120                         opt_num_short++;
121                         if (entry->flags == OPT_HASARG) {
122                                 opt_num_short_arg++;
123                                 /* FIXME: -? with ops breaks getopt_long */
124                                 assert(*p != '?');
125                         }
126                 }
127         }
128 }
129
130 static void add_opt(const struct opt_table *entry)
131 {
132         opt_table = realloc(opt_table, sizeof(opt_table[0]) * (opt_count+1));
133         opt_table[opt_count++] = *entry;
134 }
135
136 void _opt_register(const char *names, enum opt_flags flags,
137                    char *(*cb)(void *arg),
138                    char *(*cb_arg)(const char *optarg, void *arg),
139                    void (*show)(char buf[OPT_SHOW_LEN], const void *arg),
140                    void *arg, const char *desc)
141 {
142         struct opt_table opt;
143         opt.names = names;
144         opt.flags = flags;
145         opt.cb = cb;
146         opt.cb_arg = cb_arg;
147         opt.show = show;
148         opt.arg = arg;
149         opt.desc = desc;
150         check_opt(&opt);
151         add_opt(&opt);
152 }
153
154 void opt_register_table(const struct opt_table entry[], const char *desc)
155 {
156         unsigned int i, start = opt_count;
157
158         if (desc) {
159                 struct opt_table heading = OPT_SUBTABLE(NULL, desc);
160                 add_opt(&heading);
161         }
162         for (i = 0; entry[i].flags != OPT_END; i++) {
163                 if (entry[i].flags == OPT_SUBTABLE)
164                         opt_register_table(subtable_of(&entry[i]),
165                                            entry[i].desc);
166                 else {
167                         check_opt(&entry[i]);
168                         add_opt(&entry[i]);
169                 }
170         }
171         /* We store the table length in arg ptr. */
172         if (desc)
173                 opt_table[start].arg = (void *)(intptr_t)(opt_count - start);
174 }
175
176 static char *make_optstring(void)
177 {
178         char *str = malloc(1 + opt_num_short + opt_num_short_arg + 1);
179         const char *p;
180         unsigned int i, num = 0;
181
182         /* This tells getopt_long we want a ':' returned for missing arg. */
183         str[num++] = ':';
184         for (p = first_sopt(&i); p; p = next_sopt(p, &i)) {
185                 str[num++] = *p;
186                 if (opt_table[i].flags == OPT_HASARG)
187                         str[num++] = ':';
188         }
189         str[num++] = '\0';
190         assert(num == 1 + opt_num_short + opt_num_short_arg + 1);
191         return str;
192 }
193
194 static struct option *make_options(void)
195 {
196         struct option *options = malloc(sizeof(*options) * (opt_num_long + 1));
197         unsigned int i, num = 0, len;
198         const char *p;
199
200         for (p = first_lopt(&i, &len); p; p = next_lopt(p, &i, &len)) {
201                 char *buf = malloc(len + 1);
202                 memcpy(buf, p, len);
203                 buf[len] = 0;
204                 options[num].name = buf;
205                 options[num].has_arg = (opt_table[i].flags == OPT_HASARG);
206                 options[num].flag = NULL;
207                 options[num].val = 0;
208                 num++;
209         }
210         memset(&options[num], 0, sizeof(options[num]));
211         assert(num == opt_num_long);
212         return options;
213 }
214
215 static struct opt_table *find_short(char shortopt)
216 {
217         unsigned int i;
218         const char *p;
219
220         for (p = first_sopt(&i); p; p = next_sopt(p, &i)) {
221                 if (*p == shortopt)
222                         return &opt_table[i];
223         }
224         abort();
225 }
226
227 /* We want the index'th long entry. */
228 static struct opt_table *find_long(int index, const char **name)
229 {
230         unsigned int i, len;
231         const char *p;
232
233         for (p = first_lopt(&i, &len); p; p = next_lopt(p, &i, &len)) {
234                 if (index == 0) {
235                         *name = p;
236                         return &opt_table[i];
237                 }
238                 index--;
239         }
240         abort();
241 }
242
243 /* glibc does this as:
244 /tmp/opt-example: invalid option -- 'x'
245 /tmp/opt-example: unrecognized option '--long'
246 /tmp/opt-example: option '--someflag' doesn't allow an argument
247 /tmp/opt-example: option '--s' is ambiguous
248 /tmp/opt-example: option requires an argument -- 's'
249 */
250 static void parse_fail(void (*errlog)(const char *fmt, ...),
251                        char shortopt, const char *longopt, const char *problem)
252 {
253         if (shortopt)
254                 errlog("%s: -%c: %s", opt_argv0, shortopt, problem);
255         else
256                 errlog("%s: --%.*s: %s", opt_argv0,
257                        strcspn(longopt, "/"), longopt, problem);
258 }
259
260 /* Parse your arguments. */
261 bool opt_parse(int *argc, char *argv[], void (*errlog)(const char *fmt, ...))
262 {
263         char *optstring = make_optstring();
264         struct option *options = make_options();
265         int ret, longidx = 0;
266         struct opt_table *e;
267
268         /* We will do our own error reporting. */
269         opterr = 0;
270         opt_argv0 = argv[0];
271
272         /* Reset in case we're called more than once. */
273         optopt = 0;
274         optind = 0;
275         while ((ret = getopt_long(*argc, argv, optstring, options, &longidx))
276                != -1) {
277                 char *problem;
278                 const char *name;
279
280                 /* optopt is 0 if it's an unknown long option, *or* if
281                  * -? is a valid short option. */
282                 if (ret == '?') {
283                         if (optopt || strncmp(argv[optind-1], "--", 2) == 0) {
284                                 parse_fail(errlog, optopt, argv[optind-1]+2,
285                                            "unrecognized option");
286                                 break;
287                         }
288                 } else if (ret == ':') {
289                         /* Missing argument: longidx not updated :( */
290                         parse_fail(errlog, optopt, argv[optind-1]+2,
291                                    "option requires an argument");
292                         break;
293                 }
294
295                 if (ret != 0)
296                         e = find_short(ret);
297                 else
298                         e = find_long(longidx, &name);
299
300                 if (e->flags == OPT_HASARG)
301                         problem = e->cb_arg(optarg, e->arg);
302                 else
303                         problem = e->cb(e->arg);
304
305                 if (problem) {
306                         parse_fail(errlog, ret, name, problem);
307                         free(problem);
308                         break;
309                 }
310         }
311         free(optstring);
312         free(options);
313         if (ret != -1)
314                 return false;
315
316         /* We hide everything but remaining arguments. */
317         memmove(&argv[1], &argv[optind], sizeof(argv[1]) * (*argc-optind+1));
318         *argc -= optind - 1;
319
320         return ret == -1 ? true : false;
321 }
322
323 void opt_log_stderr(const char *fmt, ...)
324 {
325         va_list ap;
326
327         va_start(ap, fmt);
328         vfprintf(stderr, fmt, ap);
329         va_end(ap);
330 }
331
332 char *opt_invalid_argument(const char *arg)
333 {
334         char *str = malloc(sizeof("Invalid argument '%s'") + strlen(arg));
335         sprintf(str, "Invalid argument '%s'", arg);
336         return str;
337 }