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