]> git.ozlabs.org Git - ccan/blob - ccan/opt/opt.h
tdb2: unify tdb1_traverse into tdb_traverse
[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 long and short option (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  * At least one of @longopt and @shortopt must be non-zero.  If the
151  * @cb returns false, opt_parse() will stop parsing and return false.
152  *
153  * Example:
154  * static char *explode(const char *optarg, void *unused)
155  * {
156  *      errx(1, "BOOM! %s", optarg);
157  * }
158  * ...
159  *      opt_register_arg("--explode|--boom", explode, NULL, NULL, opt_hidden);
160  */
161 #define opt_register_arg(names, cb, show, arg, desc)                    \
162         _opt_register((names), OPT_CB_ARG((cb), (show), (arg)), (arg), (desc))
163
164 /**
165  * opt_parse - parse arguments.
166  * @argc: pointer to argc
167  * @argv: argv array.
168  * @errlog: the function to print errors
169  *
170  * This iterates through the command line and calls callbacks registered with
171  * opt_register_table()/opt_register_arg()/opt_register_noarg().  If there
172  * are unknown options, missing arguments or a callback returns false, then
173  * an error message is printed and false is returned.
174  *
175  * On success, argc and argv are adjusted so only the non-option elements
176  * remain, and true is returned.
177  *
178  * Example:
179  *      if (!opt_parse(&argc, argv, opt_log_stderr)) {
180  *              printf("You screwed up, aborting!\n");
181  *              exit(1);
182  *      }
183  *
184  * See Also:
185  *      opt_log_stderr, opt_log_stderr_exit
186  */
187 bool opt_parse(int *argc, char *argv[], void (*errlog)(const char *fmt, ...));
188
189 /**
190  * opt_free_table - reset the opt library.
191  *
192  * This frees the internal memory and returns counters to zero.  Call
193  * this as the last opt function to avoid memory leaks.  You can also
194  * use this function to reset option handling to its initial state (no
195  * options registered).
196  */
197 void opt_free_table(void);
198
199 /**
200  * opt_log_stderr - print message to stderr.
201  * @fmt: printf-style format.
202  *
203  * This is a helper for opt_parse, to print errors to stderr.
204  *
205  * See Also:
206  *      opt_log_stderr_exit
207  */
208 void opt_log_stderr(const char *fmt, ...);
209
210 /**
211  * opt_log_stderr_exit - print message to stderr, then exit(1)
212  * @fmt: printf-style format.
213  *
214  * Just like opt_log_stderr, only then does exit(1).  This means that
215  * when handed to opt_parse, opt_parse will never return false.
216  *
217  * Example:
218  *      // This never returns false; just exits if there's an erorr.
219  *      opt_parse(&argc, argv, opt_log_stderr_exit);
220  */
221 void opt_log_stderr_exit(const char *fmt, ...);
222
223 /**
224  * opt_invalid_argument - helper to allocate an "Invalid argument '%s'" string
225  * @arg: the argument which was invalid.
226  *
227  * This is a helper for callbacks to return a simple error string.
228  */
229 char *opt_invalid_argument(const char *arg);
230
231 /**
232  * opt_usage - create usage message
233  * @argv0: the program name
234  * @extra: extra details to print after the initial command, or NULL.
235  *
236  * Creates a usage message, with the program name, arguments, some extra details
237  * and a table of all the options with their descriptions.  If an option has
238  * description opt_hidden, it is not shown here.
239  *
240  * If "extra" is NULL, then the extra information is taken from any
241  * registered option which calls opt_usage_and_exit().  This avoids duplicating
242  * that string in the common case.
243  *
244  * The result should be passed to free().
245  */
246 char *opt_usage(const char *argv0, const char *extra);
247
248 /**
249  * opt_hidden - string for undocumented options.
250  *
251  * This can be used as the desc parameter if you want an option not to be
252  * shown by opt_usage().
253  */
254 extern const char opt_hidden[];
255
256 /* Maximum length of arg to show in opt_usage */
257 #define OPT_SHOW_LEN 80
258
259 /* Standard helpers.  You can write your own: */
260 /* Sets the @b to true. */
261 char *opt_set_bool(bool *b);
262 /* Sets @b based on arg: (yes/no/true/false). */
263 char *opt_set_bool_arg(const char *arg, bool *b);
264 void opt_show_bool(char buf[OPT_SHOW_LEN], const bool *b);
265 /* The inverse */
266 char *opt_set_invbool(bool *b);
267 void opt_show_invbool(char buf[OPT_SHOW_LEN], const bool *b);
268 /* Sets @b based on !arg: (yes/no/true/false). */
269 char *opt_set_invbool_arg(const char *arg, bool *b);
270
271 /* Set a char *. */
272 char *opt_set_charp(const char *arg, char **p);
273 void opt_show_charp(char buf[OPT_SHOW_LEN], char *const *p);
274
275 /* Set an integer value, various forms.  Sets to 1 on arg == NULL. */
276 char *opt_set_intval(const char *arg, int *i);
277 void opt_show_intval(char buf[OPT_SHOW_LEN], const int *i);
278 char *opt_set_uintval(const char *arg, unsigned int *ui);
279 void opt_show_uintval(char buf[OPT_SHOW_LEN], const unsigned int *ui);
280 char *opt_set_longval(const char *arg, long *l);
281 void opt_show_longval(char buf[OPT_SHOW_LEN], const long *l);
282 char *opt_set_ulongval(const char *arg, unsigned long *ul);
283 void opt_show_ulongval(char buf[OPT_SHOW_LEN], const unsigned long *ul);
284
285 /* the following setting functions accept k, M, G, T, P, or E suffixes, which
286    multiplies the numeric value by the corresponding power of 1000 or 1024
287    (for the _si and _bi versions, respectively).
288  */
289 char *opt_set_intval_bi(const char *arg, int *i);
290 char *opt_set_intval_si(const char *arg, int *i);
291 char *opt_set_uintval_bi(const char *arg, unsigned int *u);
292 char *opt_set_uintval_si(const char *arg, unsigned int *u);
293 char *opt_set_longval_bi(const char *arg, long *l);
294 char *opt_set_longval_si(const char *arg, long *l);
295 char *opt_set_ulongval_bi(const char *arg, unsigned long *ul);
296 char *opt_set_ulongval_si(const char *arg, unsigned long *ul);
297 char *opt_set_longlongval_bi(const char *arg, long long *ll);
298 char *opt_set_longlongval_si(const char *arg, long long *ll);
299 char *opt_set_ulonglongval_bi(const char *arg, unsigned long long *ll);
300 char *opt_set_ulonglongval_si(const char *arg, unsigned long long *ll);
301
302
303 void opt_show_intval_bi(char buf[OPT_SHOW_LEN], const int *x);
304 void opt_show_longval_bi(char buf[OPT_SHOW_LEN], const long *x);
305 void opt_show_longlongval_bi(char buf[OPT_SHOW_LEN], const long long *x);
306 void opt_show_uintval_bi(char buf[OPT_SHOW_LEN], const unsigned int *x);
307 void opt_show_ulongval_bi(char buf[OPT_SHOW_LEN], const unsigned long *x);
308 void opt_show_ulonglongval_bi(char buf[OPT_SHOW_LEN], const unsigned long long *x);
309
310 void opt_show_intval_si(char buf[OPT_SHOW_LEN], const int *x);
311 void opt_show_longval_si(char buf[OPT_SHOW_LEN], const long *x);
312 void opt_show_longlongval_si(char buf[OPT_SHOW_LEN], const long long *x);
313 void opt_show_uintval_si(char buf[OPT_SHOW_LEN], const unsigned int *x);
314 void opt_show_ulongval_si(char buf[OPT_SHOW_LEN], const unsigned long *x);
315 void opt_show_ulonglongval_si(char buf[OPT_SHOW_LEN], const unsigned long long *x);
316
317
318
319
320 /* Increment. */
321 char *opt_inc_intval(int *i);
322
323 /* Display version string to stdout, exit(0). */
324 char *opt_version_and_exit(const char *version);
325
326 /* Display usage string to stdout, exit(0). */
327 char *opt_usage_and_exit(const char *extra);
328
329 /* Below here are private declarations. */
330 /* You can use this directly to build tables, but the macros will ensure
331  * consistency and type safety. */
332 enum opt_type {
333         OPT_NOARG = 1,          /* -f|--foo */
334         OPT_HASARG = 2,         /* -f arg|--foo=arg|--foo arg */
335         OPT_SUBTABLE = 4,       /* Actually, longopt points to a subtable... */
336         OPT_END = 8,            /* End of the table. */
337 };
338
339 struct opt_table {
340         const char *names; /* pipe-separated names, --longopt or -s */
341         enum opt_type type;
342         char *(*cb)(void *arg); /* OPT_NOARG */
343         char *(*cb_arg)(const char *optarg, void *arg); /* OPT_HASARG */
344         void (*show)(char buf[OPT_SHOW_LEN], const void *arg);
345         union {
346                 const void *carg;
347                 void *arg;
348                 size_t tlen;
349         } u;
350         const char *desc;
351 };
352
353 /* Resolves to the four parameters for non-arg callbacks. */
354 #define OPT_CB_NOARG(cb, arg)                           \
355         OPT_NOARG,                                      \
356         typesafe_cb_cast3(char *(*)(void *),    \
357                           char *(*)(typeof(*(arg))*),   \
358                           char *(*)(const typeof(*(arg))*),     \
359                           char *(*)(const void *), (cb)),       \
360         NULL, NULL
361
362 /* Resolves to the four parameters for arg callbacks. */
363 #define OPT_CB_ARG(cb, show, arg)                                       \
364         OPT_HASARG, NULL,                                               \
365         typesafe_cb_cast3(char *(*)(const char *,void *),       \
366                           char *(*)(const char *, typeof(*(arg))*),     \
367                           char *(*)(const char *, const typeof(*(arg))*), \
368                           char *(*)(const char *, const void *),        \
369                           (cb)),                                        \
370         typesafe_cb_cast(void (*)(char buf[], const void *),            \
371                          void (*)(char buf[], const typeof(*(arg))*), (show))
372
373 /* Non-typesafe register function. */
374 void _opt_register(const char *names, enum opt_type type,
375                    char *(*cb)(void *arg),
376                    char *(*cb_arg)(const char *optarg, void *arg),
377                    void (*show)(char buf[OPT_SHOW_LEN], const void *arg),
378                    const void *arg, const char *desc);
379
380 /* We use this to get typechecking for OPT_SUBTABLE */
381 static inline int _check_is_entry(struct opt_table *e UNUSED) { return 0; }
382
383 #endif /* CCAN_OPT_H */