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