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