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