]> git.ozlabs.org Git - ccan/blob - ccan/opt/opt.h
opt: new module to parse commandline options.
[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_flags {
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 struct opt_table {
16         const char *longopt; /* --longopt, or NULL */
17         char shortopt; /* -s, or 0 */
18         enum opt_flags flags;
19         char *(*cb)(void *arg); /* OPT_NOARG */
20         char *(*cb_arg)(const char *optarg, void *arg); /* OPT_HASARG */
21         void *arg;
22         const char *desc;
23 };
24
25 /**
26  * OPT_WITHOUT_ARG() - macro for initializing an opt_table entry (without arg)
27  * @longopt: the name of the argument (eg. "foo" for "--foo"), or NULL.
28  * @shortopt: the character of the argument (eg. 'f' for "-f"), or 0.
29  * @cb: the callback when the option is found.
30  * @arg: the argument to hand to @cb.
31  *
32  * This is a typesafe wrapper for intializing a struct opt_table.  The callback
33  * of type "char *cb(type *)", "char *cb(const type *)" or "char *cb(void *)",
34  * where "type" is the type of the @arg argument.
35  *
36  * At least one of @longopt and @shortopt must be non-zero.  If the
37  * @cb returns non-NULL, opt_parse() will stop parsing, use the returned
38  * string to form an error message, free() the string and return false.
39  *
40  * See Also:
41  *      OPT_WITH_ARG()
42  */
43 #define OPT_WITHOUT_ARG(longopt, shortopt, cb, arg)     \
44         (longopt), (shortopt), OPT_CB_NOARG((cb), (arg))
45
46 /**
47  * OPT_WITH_ARG() - macro for initializing long and short option (with arg)
48  * @longopt: the name of the argument (eg. "foo" for "--foo <arg>"), or NULL.
49  * @shortopt: the character of the argument (eg. 'f' for "-f <arg>"), or 0.
50  * @cb: the callback when the option is found (along with <arg>).
51  * @arg: the argument to hand to @cb.
52  *
53  * This is a typesafe wrapper for intializing a struct opt_table.  The callback
54  * is of type "bool cb(const char *, type *)",
55  * "bool cb(const char *, const type *)" or "bool cb(const char *, void *)",
56  * where "type" is the type of the @arg argument.  The first argument to the
57  * @cb is the argument found on the commandline.
58  *
59  * At least one of @longopt and @shortopt must be non-zero.  If the
60  * @cb returns false, opt_parse() will stop parsing and return false.
61  *
62  * See Also:
63  *      OPT_WITH_ARG()
64  */
65 #define OPT_WITH_ARG(longopt, shortopt, cb, arg)        \
66         (longopt), (shortopt), OPT_CB_ARG((cb), (arg))
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  * The @desc field can be opt_table_hidden to hide the options from opt_usage().
74  */
75 #define OPT_SUBTABLE(table, desc)                                       \
76         { (const char *)(table), sizeof(_check_is_entry(table)),        \
77           OPT_SUBTABLE, NULL, NULL, NULL, (desc) }
78
79 /**
80  * opt_table_hidden - string for undocumented option tables.
81  *
82  * This can be used as the desc option to OPT_SUBTABLE or passed to
83  * opt_register_table() if you want the options not to be shown by
84  * opt_usage().
85  */
86 extern const char opt_table_hidden[];
87
88 /**
89  * OPT_ENDTABLE - macro to create final entry in table.
90  *
91  * This must be the final element in the opt_table array.
92  */
93 #define OPT_ENDTABLE { NULL, 0, OPT_END }
94
95 /**
96  * opt_register_table - register a table of options
97  * @table: the table of options
98  * @desc: description of this subtable (for opt_usage()) or NULL.
99  *
100  * The table must be terminated by OPT_ENDTABLE.
101  *
102  * Example:
103  * static struct opt_table opts[] = {
104  *      { OPT_WITHOUT_ARG("verbose", 'v', opt_inc_intval, &verbose),
105  *        "Verbose mode (can be specified more than once)" },
106  *      { OPT_WITHOUT_ARG("usage", 0, opt_usage_and_exit,
107  *                        "args...\nA silly test program."),
108  *        "Print this message." },
109  *      OPT_ENDTABLE
110  * };
111  *
112  * ...
113  *      opt_register_table(opts, NULL);
114  */
115 void opt_register_table(const struct opt_table table[], const char *desc);
116
117 /**
118  * opt_register_noarg - register an option with no arguments
119  * @longopt: the name of the argument (eg. "foo" for "--foo"), or NULL.
120  * @shortopt: the character of the argument (eg. 'f' for "-f"), or 0.
121  * @cb: the callback when the option is found.
122  * @arg: the argument to hand to @cb.
123  * @desc: the verbose desction of the option (for opt_usage()), or NULL.
124  *
125  * This is used for registering a single commandline option which takes
126  * no argument.
127  *
128  * The callback is of type "bool cb(type *)", "bool cb(const type *)"
129  * or "bool cb(void *)", where "type" is the type of the @arg
130  * argument.
131  *
132  * At least one of @longopt and @shortopt must be non-zero.  If the
133  * @cb returns false, opt_parse() will stop parsing and return false.
134  */
135 #define opt_register_noarg(longopt, shortopt, cb, arg, desc)    \
136         _opt_register((longopt), (shortopt), OPT_CB_NOARG((cb), (arg)), (desc))
137
138 /**
139  * opt_register_arg - register an option with an arguments
140  * @longopt: the name of the argument (eg. "foo" for "--foo"), or NULL.
141  * @shortopt: the character of the argument (eg. 'f' for "-f"), or 0.
142  * @cb: the callback when the option is found.
143  * @arg: the argument to hand to @cb.
144  * @desc: the verbose desction of the option (for opt_usage()), or NULL.
145  *
146  * This is used for registering a single commandline option which takes
147  * an argument.
148  *
149  * The callback is of type "bool cb(const char *, type *)",
150  * "bool cb(const char *, const type *)" or "bool cb(const char *, void *)",
151  * where "type" is the type of the @arg argument.  The first argument to the
152  * @cb is the argument found on the commandline.
153  *
154  * At least one of @longopt and @shortopt must be non-zero.  If the
155  * @cb returns false, opt_parse() will stop parsing and return false.
156  *
157  * Example:
158  *      opt_register_arg("explode", 'e', explode_cb, NULL,
159  *                       "Make the machine explode (developers only)");
160  */
161 #define opt_register_arg(longopt, shortopt, cb, arg, desc)      \
162         _opt_register((longopt), (shortopt), OPT_CB_ARG((cb), (arg)), (desc))
163
164 /**
165  * opt_parse - parse arguments.
166  * @argc: pointer to argc
167  * @argv: argv array.
168  * @errlog: the function to print errors (usually opt_log_stderr).
169  *
170  * This iterates through the command line and calls callbacks registered with
171  * opt_register_table()/opt_register_arg()/opt_register_noarg().  If there
172  * are unknown options, missing arguments or a callback returns false, then
173  * an error message is printed and false is returned.
174  *
175  * On success, argc and argv are adjusted so only the non-option elements
176  * remain, and true is returned.
177  *
178  * Example:
179  *      if (!opt_parse(argc, argv, opt_log_stderr)) {
180  *              printf("%s", opt_usage(argv[0], "<args>..."));
181  *              exit(1);
182  *      }
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 the standard helper for opt_parse, to print errors.
191  */
192 void opt_log_stderr(const char *fmt, ...);
193
194 /**
195  * opt_invalid_argument - helper to allocate an "Invalid argument '%s'" string
196  * @arg: the argument which was invalid.
197  *
198  * This is a helper for callbacks to return a simple error string.
199  */
200 char *opt_invalid_argument(const char *arg);
201
202 /**
203  * opt_usage - create usage message
204  * @argv0: the program name
205  * @extra: extra details to print after the initial command, or NULL.
206  *
207  * Creates a usage message, with the program name, arguments, some extra details
208  * and a table of all the options with their descriptions.
209  *
210  * The result should be passed to free().
211  */
212 char *opt_usage(const char *argv0, const char *extra);
213
214 /* Standard helpers.  You can write your own: */
215 /* Sets the @b to true. */
216 char *opt_set_bool(bool *b);
217 /* Sets @b based on arg: (yes/no/true/false). */
218 char *opt_set_bool_arg(const char *arg, bool *b);
219 /* The inverse */
220 char *opt_set_invbool(bool *b);
221 char *opt_set_invbool_arg(const char *arg, bool *b);
222
223 /* Set a char *. */
224 char *opt_set_charp(const char *arg, char **p);
225
226 /* Set an integer value, various forms.  Sets to 1 on arg == NULL. */
227 char *opt_set_intval(const char *arg, int *i);
228 char *opt_set_uintval(const char *arg, unsigned int *ui);
229 char *opt_set_longval(const char *arg, long *l);
230 char *opt_set_ulongval(const char *arg, unsigned long *ul);
231
232 /* Increment. */
233 char *opt_inc_intval(int *i);
234
235 /* Display version string to stdout, exit(0). */
236 char *opt_show_version_and_exit(const char *version);
237
238 /* Display usage string to stdout, exit(0). */
239 char *opt_usage_and_exit(const char *extra);
240
241 /* Below here are private declarations. */
242 /* Resolves to the four parameters for non-arg callbacks. */
243 #define OPT_CB_NOARG(cb, arg)                           \
244         OPT_NOARG,                                      \
245         cast_if_any(char *(*)(void *), (cb), &*(cb),    \
246                     char *(*)(typeof(*(arg))*),         \
247                     char *(*)(const typeof(*(arg))*),   \
248                     char *(*)(const typeof(*(arg))*)),  \
249         NULL, (arg)
250
251 /* Resolves to the four parameters for arg callbacks. */
252 #define OPT_CB_ARG(cb, arg)                                             \
253         OPT_HASARG, NULL,                                               \
254         cast_if_any(char *(*)(const char *,void *), (cb), &*(cb),       \
255                     char *(*)(const char *, typeof(*(arg))*),           \
256                     char *(*)(const char *, const typeof(*(arg))*),     \
257                     char *(*)(const char *, const typeof(*(arg))*)),    \
258         (arg)
259
260 /* Non-typesafe register function. */
261 void _opt_register(const char *longopt, char shortopt, enum opt_flags flags,
262                    char *(*cb)(void *arg),
263                    char *(*cb_arg)(const char *optarg, void *arg),
264                    void *arg, const char *desc);
265
266 /* We use this to get typechecking for OPT_SUBTABLE */
267 static inline int _check_is_entry(struct opt_table *e) { return 0; }
268
269 #endif /* CCAN_OPT_H */