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