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