]> git.ozlabs.org Git - ccan/blob - ccan/opt/opt.h
opt: incidental comment and whitespace repair
[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 - free the table.
191  *
192  * This frees the internal memory. Call this as the last
193  * opt function.
194  */
195 void opt_free_table(void);
196
197 /**
198  * opt_log_stderr - print message to stderr.
199  * @fmt: printf-style format.
200  *
201  * This is a helper for opt_parse, to print errors to stderr.
202  *
203  * See Also:
204  *      opt_log_stderr_exit
205  */
206 void opt_log_stderr(const char *fmt, ...);
207
208 /**
209  * opt_log_stderr_exit - print message to stderr, then exit(1)
210  * @fmt: printf-style format.
211  *
212  * Just like opt_log_stderr, only then does exit(1).  This means that
213  * when handed to opt_parse, opt_parse will never return false.
214  *
215  * Example:
216  *      // This never returns false; just exits if there's an erorr.
217  *      opt_parse(&argc, argv, opt_log_stderr_exit);
218  */
219 void opt_log_stderr_exit(const char *fmt, ...);
220
221 /**
222  * opt_invalid_argument - helper to allocate an "Invalid argument '%s'" string
223  * @arg: the argument which was invalid.
224  *
225  * This is a helper for callbacks to return a simple error string.
226  */
227 char *opt_invalid_argument(const char *arg);
228
229 /**
230  * opt_usage - create usage message
231  * @argv0: the program name
232  * @extra: extra details to print after the initial command, or NULL.
233  *
234  * Creates a usage message, with the program name, arguments, some extra details
235  * and a table of all the options with their descriptions.  If an option has
236  * description opt_hidden, it is not shown here.
237  *
238  * If "extra" is NULL, then the extra information is taken from any
239  * registered option which calls opt_usage_and_exit().  This avoids duplicating
240  * that string in the common case.
241  *
242  * The result should be passed to free().
243  */
244 char *opt_usage(const char *argv0, const char *extra);
245
246 /**
247  * opt_hidden - string for undocumented options.
248  *
249  * This can be used as the desc parameter if you want an option not to be
250  * shown by opt_usage().
251  */
252 extern const char opt_hidden[];
253
254 /* Maximum length of arg to show in opt_usage */
255 #define OPT_SHOW_LEN 80
256
257 /* Standard helpers.  You can write your own: */
258 /* Sets the @b to true. */
259 char *opt_set_bool(bool *b);
260 /* Sets @b based on arg: (yes/no/true/false). */
261 char *opt_set_bool_arg(const char *arg, bool *b);
262 void opt_show_bool(char buf[OPT_SHOW_LEN], const bool *b);
263 /* The inverse */
264 char *opt_set_invbool(bool *b);
265 void opt_show_invbool(char buf[OPT_SHOW_LEN], const bool *b);
266 /* Sets @b based on !arg: (yes/no/true/false). */
267 char *opt_set_invbool_arg(const char *arg, bool *b);
268
269 /* Set a char *. */
270 char *opt_set_charp(const char *arg, char **p);
271 void opt_show_charp(char buf[OPT_SHOW_LEN], char *const *p);
272
273 /* Set an integer value, various forms.  Sets to 1 on arg == NULL. */
274 char *opt_set_intval(const char *arg, int *i);
275 void opt_show_intval(char buf[OPT_SHOW_LEN], const int *i);
276 char *opt_set_uintval(const char *arg, unsigned int *ui);
277 void opt_show_uintval(char buf[OPT_SHOW_LEN], const unsigned int *ui);
278 char *opt_set_longval(const char *arg, long *l);
279 void opt_show_longval(char buf[OPT_SHOW_LEN], const long *l);
280 char *opt_set_ulongval(const char *arg, unsigned long *ul);
281 void opt_show_ulongval(char buf[OPT_SHOW_LEN], const unsigned long *ul);
282
283 /* the following setting functions accept k, M, G, T, P, or E suffixes, which
284    multiplies the numeric value by the corresponding power of 1000 or 1024
285    (for the _si and _bi versions, respectively).
286  */
287 char *opt_set_intval_bi(const char *arg, int *i);
288 char *opt_set_intval_si(const char *arg, int *i);
289 char *opt_set_uintval_bi(const char *arg, unsigned int *u);
290 char *opt_set_uintval_si(const char *arg, unsigned int *u);
291 char *opt_set_longval_bi(const char *arg, long *l);
292 char *opt_set_longval_si(const char *arg, long *l);
293 char *opt_set_ulongval_bi(const char *arg, unsigned long *ul);
294 char *opt_set_ulongval_si(const char *arg, unsigned long *ul);
295 char *opt_set_longlongval_bi(const char *arg, long long *ll);
296 char *opt_set_longlongval_si(const char *arg, long long *ll);
297 char *opt_set_ulonglongval_bi(const char *arg, unsigned long long *ll);
298 char *opt_set_ulonglongval_si(const char *arg, unsigned long long *ll);
299
300 /* Increment. */
301 char *opt_inc_intval(int *i);
302
303 /* Display version string to stdout, exit(0). */
304 char *opt_version_and_exit(const char *version);
305
306 /* Display usage string to stdout, exit(0). */
307 char *opt_usage_and_exit(const char *extra);
308
309 /* Below here are private declarations. */
310 /* You can use this directly to build tables, but the macros will ensure
311  * consistency and type safety. */
312 enum opt_type {
313         OPT_NOARG = 1,          /* -f|--foo */
314         OPT_HASARG = 2,         /* -f arg|--foo=arg|--foo arg */
315         OPT_SUBTABLE = 4,       /* Actually, longopt points to a subtable... */
316         OPT_END = 8,            /* End of the table. */
317 };
318
319 struct opt_table {
320         const char *names; /* pipe-separated names, --longopt or -s */
321         enum opt_type type;
322         char *(*cb)(void *arg); /* OPT_NOARG */
323         char *(*cb_arg)(const char *optarg, void *arg); /* OPT_HASARG */
324         void (*show)(char buf[OPT_SHOW_LEN], const void *arg);
325         union {
326                 const void *carg;
327                 void *arg;
328                 size_t tlen;
329         } u;
330         const char *desc;
331 };
332
333 /* Resolves to the four parameters for non-arg callbacks. */
334 #define OPT_CB_NOARG(cb, arg)                           \
335         OPT_NOARG,                                      \
336         typesafe_cb_cast3(char *(*)(void *),    \
337                           char *(*)(typeof(*(arg))*),   \
338                           char *(*)(const typeof(*(arg))*),     \
339                           char *(*)(const void *), (cb)),       \
340         NULL, NULL
341
342 /* Resolves to the four parameters for arg callbacks. */
343 #define OPT_CB_ARG(cb, show, arg)                                       \
344         OPT_HASARG, NULL,                                               \
345         typesafe_cb_cast3(char *(*)(const char *,void *),       \
346                           char *(*)(const char *, typeof(*(arg))*),     \
347                           char *(*)(const char *, const typeof(*(arg))*), \
348                           char *(*)(const char *, const void *),        \
349                           (cb)),                                        \
350         typesafe_cb_cast(void (*)(char buf[], const void *),            \
351                          void (*)(char buf[], const typeof(*(arg))*), (show))
352
353 /* Non-typesafe register function. */
354 void _opt_register(const char *names, enum opt_type type,
355                    char *(*cb)(void *arg),
356                    char *(*cb_arg)(const char *optarg, void *arg),
357                    void (*show)(char buf[OPT_SHOW_LEN], const void *arg),
358                    const void *arg, const char *desc);
359
360 /* We use this to get typechecking for OPT_SUBTABLE */
361 static inline int _check_is_entry(struct opt_table *e UNUSED) { return 0; }
362
363 #endif /* CCAN_OPT_H */