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