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