]> git.ozlabs.org Git - ccan/blob - ccan/opt/opt.c
e7ebc3dd0550e2181b13c41438ddeb9e8f244dff
[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] == ' ' || names[0] == '=' || names[0] == '\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                 /* Don't document args unless there are some. */
128                 if (entry->flags == OPT_NOARG)
129                         assert(p[len] != ' ' && p[len] != '=');
130         }
131 }
132
133 static void add_opt(const struct opt_table *entry)
134 {
135         opt_table = realloc(opt_table, sizeof(opt_table[0]) * (opt_count+1));
136         opt_table[opt_count++] = *entry;
137 }
138
139 void _opt_register(const char *names, enum opt_flags flags,
140                    char *(*cb)(void *arg),
141                    char *(*cb_arg)(const char *optarg, void *arg),
142                    void (*show)(char buf[OPT_SHOW_LEN], const void *arg),
143                    void *arg, const char *desc)
144 {
145         struct opt_table opt;
146         opt.names = names;
147         opt.flags = flags;
148         opt.cb = cb;
149         opt.cb_arg = cb_arg;
150         opt.show = show;
151         opt.arg = arg;
152         opt.desc = desc;
153         check_opt(&opt);
154         add_opt(&opt);
155 }
156
157 void opt_register_table(const struct opt_table entry[], const char *desc)
158 {
159         unsigned int i, start = opt_count;
160
161         if (desc) {
162                 struct opt_table heading = OPT_SUBTABLE(NULL, desc);
163                 add_opt(&heading);
164         }
165         for (i = 0; entry[i].flags != OPT_END; i++) {
166                 if (entry[i].flags == OPT_SUBTABLE)
167                         opt_register_table(subtable_of(&entry[i]),
168                                            entry[i].desc);
169                 else {
170                         check_opt(&entry[i]);
171                         add_opt(&entry[i]);
172                 }
173         }
174         /* We store the table length in arg ptr. */
175         if (desc)
176                 opt_table[start].arg = (void *)(intptr_t)(opt_count - start);
177 }
178
179 static char *make_optstring(void)
180 {
181         char *str = malloc(1 + opt_num_short + opt_num_short_arg + 1);
182         const char *p;
183         unsigned int i, num = 0;
184
185         /* This tells getopt_long we want a ':' returned for missing arg. */
186         str[num++] = ':';
187         for (p = first_sopt(&i); p; p = next_sopt(p, &i)) {
188                 str[num++] = *p;
189                 if (opt_table[i].flags == OPT_HASARG)
190                         str[num++] = ':';
191         }
192         str[num++] = '\0';
193         assert(num == 1 + opt_num_short + opt_num_short_arg + 1);
194         return str;
195 }
196
197 static struct option *make_options(void)
198 {
199         struct option *options = malloc(sizeof(*options) * (opt_num_long + 1));
200         unsigned int i, num = 0, len;
201         const char *p;
202
203         for (p = first_lopt(&i, &len); p; p = next_lopt(p, &i, &len)) {
204                 char *buf = malloc(len + 1);
205                 memcpy(buf, p, len);
206                 buf[len] = 0;
207                 options[num].name = buf;
208                 options[num].has_arg = (opt_table[i].flags == OPT_HASARG);
209                 options[num].flag = NULL;
210                 options[num].val = 0;
211                 num++;
212         }
213         memset(&options[num], 0, sizeof(options[num]));
214         assert(num == opt_num_long);
215         return options;
216 }
217
218 static struct opt_table *find_short(char shortopt)
219 {
220         unsigned int i;
221         const char *p;
222
223         for (p = first_sopt(&i); p; p = next_sopt(p, &i)) {
224                 if (*p == shortopt)
225                         return &opt_table[i];
226         }
227         abort();
228 }
229
230 /* We want the index'th long entry. */
231 static struct opt_table *find_long(int index, const char **name)
232 {
233         unsigned int i, len;
234         const char *p;
235
236         for (p = first_lopt(&i, &len); p; p = next_lopt(p, &i, &len)) {
237                 if (index == 0) {
238                         *name = p;
239                         return &opt_table[i];
240                 }
241                 index--;
242         }
243         abort();
244 }
245
246 /* glibc does this as:
247 /tmp/opt-example: invalid option -- 'x'
248 /tmp/opt-example: unrecognized option '--long'
249 /tmp/opt-example: option '--someflag' doesn't allow an argument
250 /tmp/opt-example: option '--s' is ambiguous
251 /tmp/opt-example: option requires an argument -- 's'
252 */
253 static void parse_fail(void (*errlog)(const char *fmt, ...),
254                        char shortopt, const char *longopt, const char *problem)
255 {
256         if (shortopt)
257                 errlog("%s: -%c: %s", opt_argv0, shortopt, problem);
258         else
259                 errlog("%s: --%.*s: %s", opt_argv0,
260                        strcspn(longopt, "/"), longopt, problem);
261 }
262
263 /* Parse your arguments. */
264 bool opt_parse(int *argc, char *argv[], void (*errlog)(const char *fmt, ...))
265 {
266         char *optstring = make_optstring();
267         struct option *options = make_options();
268         int ret, longidx = 0;
269         struct opt_table *e;
270
271         /* We will do our own error reporting. */
272         opterr = 0;
273         opt_argv0 = argv[0];
274
275         /* Reset in case we're called more than once. */
276         optopt = 0;
277         optind = 0;
278         while ((ret = getopt_long(*argc, argv, optstring, options, &longidx))
279                != -1) {
280                 char *problem;
281                 const char *name;
282
283                 /* optopt is 0 if it's an unknown long option, *or* if
284                  * -? is a valid short option. */
285                 if (ret == '?') {
286                         if (optopt || strncmp(argv[optind-1], "--", 2) == 0) {
287                                 parse_fail(errlog, optopt, argv[optind-1]+2,
288                                            "unrecognized option");
289                                 break;
290                         }
291                 } else if (ret == ':') {
292                         /* Missing argument: longidx not updated :( */
293                         parse_fail(errlog, optopt, argv[optind-1]+2,
294                                    "option requires an argument");
295                         break;
296                 }
297
298                 if (ret != 0)
299                         e = find_short(ret);
300                 else
301                         e = find_long(longidx, &name);
302
303                 if (e->flags == OPT_HASARG)
304                         problem = e->cb_arg(optarg, e->arg);
305                 else
306                         problem = e->cb(e->arg);
307
308                 if (problem) {
309                         parse_fail(errlog, ret, name, problem);
310                         free(problem);
311                         break;
312                 }
313         }
314         free(optstring);
315         free(options);
316         if (ret != -1)
317                 return false;
318
319         /* We hide everything but remaining arguments. */
320         memmove(&argv[1], &argv[optind], sizeof(argv[1]) * (*argc-optind+1));
321         *argc -= optind - 1;
322
323         return ret == -1 ? true : false;
324 }
325
326 void opt_log_stderr(const char *fmt, ...)
327 {
328         va_list ap;
329
330         va_start(ap, fmt);
331         vfprintf(stderr, fmt, ap);
332         va_end(ap);
333 }
334
335 char *opt_invalid_argument(const char *arg)
336 {
337         char *str = malloc(sizeof("Invalid argument '%s'") + strlen(arg));
338         sprintf(str, "Invalid argument '%s'", arg);
339         return str;
340 }