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