]> git.ozlabs.org Git - ccan/blob - ccan/opt/opt.h
e7896340d32a5fbf56988ca13b456f6c71597860
[ccan] / ccan / opt / opt.h
1 /* Licensed under GPLv3+ - see LICENSE file for details */
2 #ifndef CCAN_OPT_H
3 #define CCAN_OPT_H
4 #include <ccan/compiler/compiler.h>
5 #include <ccan/typesafe_cb/typesafe_cb.h>
6 #include <stdbool.h>
7 #include <stdlib.h>
8
9 struct opt_table;
10
11 /**
12  * OPT_WITHOUT_ARG() - macro for initializing an opt_table entry (without arg)
13  * @names: the names of the option eg. "--foo", "-f" or "--foo|-f|--foobar".
14  * @cb: the callback when the option is found.
15  * @arg: the argument to hand to @cb.
16  * @desc: the description for opt_usage(), or opt_hidden.
17  *
18  * This is a typesafe wrapper for initializing a struct opt_table.  The callback
19  * of type "char *cb(type *)", "char *cb(const type *)" or "char *cb(void *)",
20  * where "type" is the type of the @arg argument.
21  *
22  * If the @cb returns non-NULL, opt_parse() will stop parsing, use the
23  * returned string to form an error message for errlog(), free() the
24  * string and return false.
25  *
26  * Any number of equivalent short or long options can be listed in @names,
27  * separated by '|'.  Short options are a single hyphen followed by a single
28  * character, long options are two hyphens followed by one or more characters.
29  *
30  * See Also:
31  *      OPT_WITH_ARG()
32  */
33 #define OPT_WITHOUT_ARG(names, cb, arg, desc)   \
34         { (names), OPT_CB_NOARG((cb), (arg)), { (arg) }, (desc) }
35
36 /**
37  * OPT_WITH_ARG() - macro for initializing an opt_table entry (with arg)
38  * @names: the option names eg. "--foo=<arg>", "-f" or "-f|--foo <arg>".
39  * @cb: the callback when the option is found (along with <arg>).
40  * @show: the callback to print the value in get_usage (or NULL)
41  * @arg: the argument to hand to @cb and @show
42  * @desc: the description for opt_usage(), or opt_hidden.
43  *
44  * This is a typesafe wrapper for initializing a struct opt_table.  The callback
45  * is of type "char *cb(const char *, type *)",
46  * "char *cb(const char *, const type *)" or "char *cb(const char *, void *)",
47  * where "type" is the type of the @arg argument.  The first argument to the
48  * @cb is the argument found on the commandline.
49  *
50  * Similarly, if @show is not NULL, it should be of type "void *show(char *,
51  * const type *)".  It should write up to OPT_SHOW_LEN bytes into the first
52  * argument; unless it uses the entire OPT_SHOW_LEN bytes it should
53  * nul-terminate that buffer.
54  *
55  * Any number of equivalent short or long options can be listed in @names,
56  * separated by '|'.  Short options are a single hyphen followed by a single
57  * character, long options are two hyphens followed by one or more characters.
58  * A space or equals in @names is ignored for parsing, and only used
59  * for printing the usage.
60  *
61  * If the @cb returns non-NULL, opt_parse() will stop parsing, use the
62  * returned string to form an error message for errlog(), free() the
63  * string and return false.
64  *
65  * See Also:
66  *      OPT_WITHOUT_ARG()
67  */
68 #define OPT_WITH_ARG(name, cb, show, arg, desc) \
69         { (name), OPT_CB_ARG((cb), (show), (arg)), { (arg) }, (desc) }
70
71 /**
72  * OPT_SUBTABLE() - macro for including another table inside a table.
73  * @table: the table to include in this table.
74  * @desc: description of this subtable (for opt_usage()) or NULL.
75  */
76 #define OPT_SUBTABLE(table, desc)                                       \
77         { (const char *)(table), OPT_SUBTABLE,                          \
78           sizeof(_check_is_entry(table)) ? NULL : NULL, NULL, NULL,     \
79           { NULL }, (desc) }
80
81 /**
82  * OPT_ENDTABLE - macro to create final entry in table.
83  *
84  * This must be the final element in the opt_table array.
85  */
86 #define OPT_ENDTABLE { NULL, OPT_END, NULL, NULL, NULL, { NULL }, NULL }
87
88 /**
89  * opt_register_table - register a table of options
90  * @table: the table of options
91  * @desc: description of this subtable (for opt_usage()) or NULL.
92  *
93  * The table must be terminated by OPT_ENDTABLE.
94  *
95  * Example:
96  * static int verbose = 0;
97  * static struct opt_table opts[] = {
98  *      OPT_WITHOUT_ARG("--verbose", opt_inc_intval, &verbose,
99  *                      "Verbose mode (can be specified more than once)"),
100  *      OPT_WITHOUT_ARG("-v", opt_inc_intval, &verbose,
101  *                      "Verbose mode (can be specified more than once)"),
102  *      OPT_WITHOUT_ARG("--usage", opt_usage_and_exit,
103  *                      "args...\nA silly test program.",
104  *                      "Print this message."),
105  *      OPT_ENDTABLE
106  * };
107  *
108  * ...
109  *      opt_register_table(opts, NULL);
110  */
111 void opt_register_table(const struct opt_table *table, const char *desc);
112
113 /**
114  * opt_register_noarg - register an option with no arguments
115  * @names: the names of the option eg. "--foo", "-f" or "--foo|-f|--foobar".
116  * @cb: the callback when the option is found.
117  * @arg: the argument to hand to @cb.
118  * @desc: the verbose description of the option (for opt_usage()), or NULL.
119  *
120  * This is used for registering a single commandline option which takes
121  * no argument.
122  *
123  * The callback is of type "char *cb(type *)", "char *cb(const type *)"
124  * or "char *cb(void *)", where "type" is the type of the @arg
125  * argument.
126  *
127  * If the @cb returns non-NULL, opt_parse() will stop parsing, use the
128  * returned string to form an error message for errlog(), free() the
129  * string and return false.
130  */
131 #define opt_register_noarg(names, cb, arg, desc)                        \
132         _opt_register((names), OPT_CB_NOARG((cb), (arg)), (arg), (desc))
133
134 /**
135  * opt_register_arg - register an option with an arguments
136  * @names: the names of the option eg. "--foo", "-f" or "--foo|-f|--foobar".
137  * @cb: the callback when the option is found.
138  * @show: the callback to print the value in get_usage (or NULL)
139  * @arg: the argument to hand to @cb.
140  * @desc: the verbose description of the option (for opt_usage()), or NULL.
141  *
142  * This is used for registering a single commandline option which takes
143  * an argument.
144  *
145  * The callback is of type "char *cb(const char *, type *)",
146  * "char *cb(const char *, const type *)" or "char *cb(const char *, void *)",
147  * where "type" is the type of the @arg argument.  The first argument to the
148  * @cb is the argument found on the commandline.
149  *
150  * If the @cb returns non-NULL, opt_parse() will stop parsing, use the
151  * returned string to form an error message for errlog(), free() the
152  * string and return false.
153  *
154  * Example:
155  * static char *explode(const char *optarg, void *unused)
156  * {
157  *      errx(1, "BOOM! %s", optarg);
158  * }
159  * ...
160  *      opt_register_arg("--explode|--boom", explode, NULL, NULL, opt_hidden);
161  */
162 #define opt_register_arg(names, cb, show, arg, desc)                    \
163         _opt_register((names), OPT_CB_ARG((cb), (show), (arg)), (arg), (desc))
164
165 /**
166  * opt_parse - parse arguments.
167  * @argc: pointer to argc
168  * @argv: argv array.
169  * @errlog: the function to print errors
170  *
171  * This iterates through the command line and calls callbacks registered with
172  * opt_register_table()/opt_register_arg()/opt_register_noarg().  As this
173  * occurs successfully each option is removed from argc and argv.
174  *
175  * If there are unknown options, missing arguments or a callback
176  * returns false, then an error message is printed and false is
177  * returned: the erroneous option is not removed.
178  *
179  * On success, argc and argv will contain only the non-option
180  * elements, and true is returned.
181  *
182  * Example:
183  *      if (!opt_parse(&argc, argv, opt_log_stderr)) {
184  *              printf("You screwed up, aborting!\n");
185  *              exit(1);
186  *      }
187  *
188  * See Also:
189  *      opt_log_stderr, opt_log_stderr_exit
190  */
191 bool opt_parse(int *argc, char *argv[], void (*errlog)(const char *fmt, ...));
192
193 /**
194  * opt_free_table - reset the opt library.
195  *
196  * This frees the internal memory and returns counters to zero.  Call
197  * this as the last opt function to avoid memory leaks.  You can also
198  * use this function to reset option handling to its initial state (no
199  * options registered).
200  */
201 void opt_free_table(void);
202
203 /**
204  * opt_log_stderr - print message to stderr.
205  * @fmt: printf-style format.
206  *
207  * This is a helper for opt_parse, to print errors to stderr.
208  *
209  * See Also:
210  *      opt_log_stderr_exit
211  */
212 void opt_log_stderr(const char *fmt, ...);
213
214 /**
215  * opt_log_stderr_exit - print message to stderr, then exit(1)
216  * @fmt: printf-style format.
217  *
218  * Just like opt_log_stderr, only then does exit(1).  This means that
219  * when handed to opt_parse, opt_parse will never return false.
220  *
221  * Example:
222  *      // This never returns false; just exits if there's an erorr.
223  *      opt_parse(&argc, argv, opt_log_stderr_exit);
224  */
225 void opt_log_stderr_exit(const char *fmt, ...);
226
227 /**
228  * opt_invalid_argument - helper to allocate an "Invalid argument '%s'" string
229  * @arg: the argument which was invalid.
230  *
231  * This is a helper for callbacks to return a simple error string.
232  */
233 char *opt_invalid_argument(const char *arg);
234
235 /**
236  * opt_usage - create usage message
237  * @argv0: the program name
238  * @extra: extra details to print after the initial command, or NULL.
239  *
240  * Creates a usage message, with the program name, arguments, some extra details
241  * and a table of all the options with their descriptions.  If an option has
242  * description opt_hidden, it is not shown here.
243  *
244  * If "extra" is NULL, then the extra information is taken from any
245  * registered option which calls opt_usage_and_exit().  This avoids duplicating
246  * that string in the common case.
247  *
248  * The result should be passed to free().
249  */
250 char *opt_usage(const char *argv0, const char *extra);
251
252 /**
253  * opt_hidden - string for undocumented options.
254  *
255  * This can be used as the desc parameter if you want an option not to be
256  * shown by opt_usage().
257  */
258 extern const char opt_hidden[];
259
260 /* Maximum length of arg to show in opt_usage */
261 #define OPT_SHOW_LEN 80
262
263 /* Standard helpers.  You can write your own: */
264 /* Sets the @b to true. */
265 char *opt_set_bool(bool *b);
266 /* Sets @b based on arg: (yes/no/true/false). */
267 char *opt_set_bool_arg(const char *arg, bool *b);
268 void opt_show_bool(char buf[OPT_SHOW_LEN], const bool *b);
269 /* The inverse */
270 char *opt_set_invbool(bool *b);
271 void opt_show_invbool(char buf[OPT_SHOW_LEN], const bool *b);
272 /* Sets @b based on !arg: (yes/no/true/false). */
273 char *opt_set_invbool_arg(const char *arg, bool *b);
274
275 /* Set a char *. */
276 char *opt_set_charp(const char *arg, char **p);
277 void opt_show_charp(char buf[OPT_SHOW_LEN], char *const *p);
278
279 /* Set an integer value, various forms.  Sets to 1 on arg == NULL. */
280 char *opt_set_intval(const char *arg, int *i);
281 void opt_show_intval(char buf[OPT_SHOW_LEN], const int *i);
282 char *opt_set_uintval(const char *arg, unsigned int *ui);
283 void opt_show_uintval(char buf[OPT_SHOW_LEN], const unsigned int *ui);
284 char *opt_set_longval(const char *arg, long *l);
285 void opt_show_longval(char buf[OPT_SHOW_LEN], const long *l);
286 char *opt_set_ulongval(const char *arg, unsigned long *ul);
287 void opt_show_ulongval(char buf[OPT_SHOW_LEN], const unsigned long *ul);
288
289 /* the following setting functions accept k, M, G, T, P, or E suffixes, which
290    multiplies the numeric value by the corresponding power of 1000 or 1024
291    (for the _si and _bi versions, respectively).
292  */
293 char *opt_set_intval_bi(const char *arg, int *i);
294 char *opt_set_intval_si(const char *arg, int *i);
295 char *opt_set_uintval_bi(const char *arg, unsigned int *u);
296 char *opt_set_uintval_si(const char *arg, unsigned int *u);
297 char *opt_set_longval_bi(const char *arg, long *l);
298 char *opt_set_longval_si(const char *arg, long *l);
299 char *opt_set_ulongval_bi(const char *arg, unsigned long *ul);
300 char *opt_set_ulongval_si(const char *arg, unsigned long *ul);
301 char *opt_set_longlongval_bi(const char *arg, long long *ll);
302 char *opt_set_longlongval_si(const char *arg, long long *ll);
303 char *opt_set_ulonglongval_bi(const char *arg, unsigned long long *ll);
304 char *opt_set_ulonglongval_si(const char *arg, unsigned long long *ll);
305
306
307 void opt_show_intval_bi(char buf[OPT_SHOW_LEN], const int *x);
308 void opt_show_longval_bi(char buf[OPT_SHOW_LEN], const long *x);
309 void opt_show_longlongval_bi(char buf[OPT_SHOW_LEN], const long long *x);
310 void opt_show_uintval_bi(char buf[OPT_SHOW_LEN], const unsigned int *x);
311 void opt_show_ulongval_bi(char buf[OPT_SHOW_LEN], const unsigned long *x);
312 void opt_show_ulonglongval_bi(char buf[OPT_SHOW_LEN], const unsigned long long *x);
313
314 void opt_show_intval_si(char buf[OPT_SHOW_LEN], const int *x);
315 void opt_show_longval_si(char buf[OPT_SHOW_LEN], const long *x);
316 void opt_show_longlongval_si(char buf[OPT_SHOW_LEN], const long long *x);
317 void opt_show_uintval_si(char buf[OPT_SHOW_LEN], const unsigned int *x);
318 void opt_show_ulongval_si(char buf[OPT_SHOW_LEN], const unsigned long *x);
319 void opt_show_ulonglongval_si(char buf[OPT_SHOW_LEN], const unsigned long long *x);
320
321
322
323
324 /* Increment. */
325 char *opt_inc_intval(int *i);
326
327 /* Display version string to stdout, exit(0). */
328 char *opt_version_and_exit(const char *version);
329
330 /* Display usage string to stdout, exit(0). */
331 char *opt_usage_and_exit(const char *extra);
332
333 /* Below here are private declarations. */
334 /* You can use this directly to build tables, but the macros will ensure
335  * consistency and type safety. */
336 enum opt_type {
337         OPT_NOARG = 1,          /* -f|--foo */
338         OPT_HASARG = 2,         /* -f arg|--foo=arg|--foo arg */
339         OPT_SUBTABLE = 4,       /* Actually, longopt points to a subtable... */
340         OPT_END = 8,            /* End of the table. */
341 };
342
343 struct opt_table {
344         const char *names; /* pipe-separated names, --longopt or -s */
345         enum opt_type type;
346         char *(*cb)(void *arg); /* OPT_NOARG */
347         char *(*cb_arg)(const char *optarg, void *arg); /* OPT_HASARG */
348         void (*show)(char buf[OPT_SHOW_LEN], const void *arg);
349         union {
350                 const void *carg;
351                 void *arg;
352                 size_t tlen;
353         } u;
354         const char *desc;
355 };
356
357 /* Resolves to the four parameters for non-arg callbacks. */
358 #define OPT_CB_NOARG(cb, arg)                           \
359         OPT_NOARG,                                      \
360         typesafe_cb_cast3(char *(*)(void *),    \
361                           char *(*)(typeof(*(arg))*),   \
362                           char *(*)(const typeof(*(arg))*),     \
363                           char *(*)(const void *), (cb)),       \
364         NULL, NULL
365
366 /* Resolves to the four parameters for arg callbacks. */
367 #define OPT_CB_ARG(cb, show, arg)                                       \
368         OPT_HASARG, NULL,                                               \
369         typesafe_cb_cast3(char *(*)(const char *,void *),       \
370                           char *(*)(const char *, typeof(*(arg))*),     \
371                           char *(*)(const char *, const typeof(*(arg))*), \
372                           char *(*)(const char *, const void *),        \
373                           (cb)),                                        \
374         typesafe_cb_cast(void (*)(char buf[], const void *),            \
375                          void (*)(char buf[], const typeof(*(arg))*), (show))
376
377 /* Non-typesafe register function. */
378 void _opt_register(const char *names, enum opt_type type,
379                    char *(*cb)(void *arg),
380                    char *(*cb_arg)(const char *optarg, void *arg),
381                    void (*show)(char buf[OPT_SHOW_LEN], const void *arg),
382                    const void *arg, const char *desc);
383
384 /* We use this to get typechecking for OPT_SUBTABLE */
385 static inline int _check_is_entry(struct opt_table *e UNUSED) { return 0; }
386
387 #endif /* CCAN_OPT_H */