]> mj.ucw.cz Git - libucw.git/blob - ucw/opt.h
Strtonum: Support u32 and s32
[libucw.git] / ucw / opt.h
1 /*
2  *      UCW Library -- Parsing of command line options
3  *
4  *      (c) 2013 Jan Moskyto Matejka <mq@ucw.cz>
5  *      (c) 2014 Martin Mares <mj@ucw.cz>
6  *      (c) 2014 Pavel Charvat <pchar@ucw.cz>
7  *
8  *      This software may be freely distributed and used according to the terms
9  *      of the GNU Lesser General Public License.
10  */
11
12 #ifndef _UCW_OPT_H
13 #define _UCW_OPT_H
14
15 #include <ucw/lib.h>
16 #include <ucw/conf.h>
17
18 #include <stdlib.h>
19 #include <stdio.h>
20
21 #ifdef CONFIG_UCW_CLEAN_ABI
22 #define cf_def_file ucw_cf_def_file
23 #define cf_env_file ucw_cf_env_file
24 #define opt_conf_hook_internal ucw_opt_conf_hook_internal
25 #define opt_failure ucw_opt_failure
26 #define opt_handle_config ucw_opt_handle_config
27 #define opt_handle_dumpconfig ucw_opt_handle_dumpconfig
28 #define opt_handle_help ucw_opt_handle_help
29 #define opt_handle_set ucw_opt_handle_set
30 #define opt_help ucw_opt_help
31 #define opt_parse ucw_opt_parse
32 #endif
33
34 #define OPT_EXIT_BAD_ARGS 2
35
36 /***
37  * [[classes]]
38  * Option classes
39  * --------------
40  *
41  * Each option belongs to one of the following classes, which define
42  * the overall behavior of the option. In most cases, the classes
43  * are set automatically by <<macros,declaration macros>>.
44  *
45  * - `OPT_CL_END`: this is not a real option class, but a signal
46  *   that the list of options ends.
47  * - `OPT_CL_BOOL`: a boolean option. If specified without an argument,
48  *   it sets the corresponding variable to 1 (true). So does an argument of
49  *   `1`, `y`, `yes`, or `true`. Conversely, an argument of `0`, `n`, `no`,
50  *   or `false` sets the variable to 0 (false) and the same happens if
51  *   the option is given as `--no-`'option' with no argument.
52  * - `OPT_CL_STATIC`: options of this class just take a value and store
53  *   it in the variable.
54  * - `OPT_CL_MULTIPLE`: collect values from all occurrences of this
55  *   option in a growing array (see `gary.h`).
56  * - `OPT_CL_SWITCH`: a multiple-choice switch, which sets the variable
57  *   to a fixed value provided in option definition.
58  * - `OPT_CL_INC`: increments the variable (or decrements, if the
59  *   `OPT_NEGATIVE` flag is set).
60  * - `OPT_CL_CALL`: instead of setting a variable, call a function
61  *   and pass the value of the option to it.
62  * - `OPT_CL_SECTION`: not a real option, but an instruction to insert
63  *   contents of another list of options.
64  * - `OPT_CL_HELP`: no option, just print a help text.
65  * - `OPT_CL_HOOK`: no option, but a definition of a <<hooks,hook>>.
66  * - `OPT_CL_BREAK`: when a given option occurs, stop parsing and keep
67  *   the option in the argument list.
68  ***/
69
70 enum opt_class {
71   OPT_CL_END,
72   OPT_CL_BOOL,
73   OPT_CL_STATIC,
74   OPT_CL_MULTIPLE,
75   OPT_CL_SWITCH,
76   OPT_CL_INC,
77   OPT_CL_CALL,
78   OPT_CL_SECTION,
79   OPT_CL_HELP,
80   OPT_CL_HOOK,
81   OPT_CL_BREAK,
82 };
83
84 /***
85  * [[opt_item]]
86  * Option definitions
87  * ------------------
88  *
89  * The list of options is represented by `struct opt_section`, which points to
90  * a sequence of `struct opt_item`s.
91  *
92  * These structures are seldom used directly -- instead, they are produced
93  * by <<macros,declaration macros>>.
94  ***/
95
96 /** A section of option list. **/
97 struct opt_section {
98   const struct opt_item * opt;
99 };
100
101 /** A definition of a single option item. **/
102 struct opt_item {
103   const char * name;                    // long name (NULL if none)
104   int letter;                           // short name (0 if none)
105   void * ptr;                           // variable to store the value to
106   const char * help;                    // description in --help (NULL to omit the option from the help)
107   union opt_union {
108     const struct opt_section * section; // subsection for OPT_CL_SECTION
109     int value;                          // value for OPT_CL_SWITCH
110     void (* call)(const struct opt_item * opt, const char * value, void * data);                // function to call for OPT_CL_CALL
111     void (* hook)(const struct opt_item * opt, uint event, const char * value, void * data);    // function to call for OPT_CL_HOOK
112     struct cf_user_type * utype;        // specification of the user-defined type for CT_USER
113   } u;
114   u16 flags;                            // as defined below (for hooks, event mask is stored instead)
115   byte cls;                             // enum opt_class
116   byte type;                            // enum cf_type
117 };
118
119 /***
120  * [[flags]]
121  * Option flags
122  * ------------
123  *
124  * Each option can specify a combination of the following flags.
125  ***/
126
127 #define OPT_REQUIRED        0x1         /** The option must be always present. **/
128 #define OPT_REQUIRED_VALUE  0x2         /** The option must have a value. **/
129 #define OPT_NO_VALUE        0x4         /** The option must have no value. **/
130 #define OPT_MAYBE_VALUE     0x8         /** The option may have a value. **/
131 #define OPT_NEGATIVE        0x10        /** Reversing the effect of OPT_INC or saving @false into OPT_BOOL. **/
132 #define OPT_LAST_ARG        0x40        /** Stop processing arguments after this line. **/
133 #define OPT_SINGLE          0x100       /** The option must appear at most once. **/
134 #define OPT_MULTIPLE        0x200       /** The option may appear multiple times; will save all the values into a simple list. **/
135 #define OPT_SEEN_AS_LONG    0x400       // Used internally to signal that we currently process the long form of the option
136 #define OPT_BEFORE_CONFIG   0x800       /** The option may appear before a config file is loaded. **/
137 #define OPT_HELP_COL        0x1000      /** Used for OPT_CL_HELP to signal that tabs switch columns. **/
138 #define OPT_INTERNAL        0x4000      // Used internally to ask for passing of struct opt_context to OPT_CALL
139
140 /**
141  * If none of these flags are specified, a default is chosen automatically
142  * according to option class:
143  *
144  * - `OPT_MAYBE_VALUE` for `OPT_CL_STATIC`
145  * - `OPT_REQUIRED_VALUE` for `OPT_CL_MULTIPLE`
146  * - `OPT_NO_VALUE` for `OPT_CL_BOOL`, `OPT_CL_SWITCH` and `OPT_CL_INC`
147  * - An error is reported in all other cases.
148  **/
149 #define OPT_VALUE_FLAGS     (OPT_REQUIRED_VALUE | OPT_NO_VALUE | OPT_MAYBE_VALUE)
150
151 /***
152  * [[macros]]
153  * Macros for declaration of options
154  * ---------------------------------
155  *
156  * In most cases, option definitions are built using these macros.
157  ***/
158
159 /** Used inside `struct opt_section` to start a list of items. **/
160 #define OPT_ITEMS       .opt = ( struct opt_item[] )
161
162 /** No option, just a piece of help text. **/
163 #define OPT_HELP(line) { .help = line, .cls = OPT_CL_HELP }
164
165 /** Like OPT_HELP, but the help text uses tab characters to switch columns like help text for ordinary options does. **/
166 #define OPT_HELP_COLUMNS(line) { .help = line, .flags = OPT_HELP_COL, .cls = OPT_CL_HELP }
167
168 /** Standard `--help` option. **/
169 #define OPT_HELP_OPTION OPT_CALL(0, "help", opt_handle_help, NULL, OPT_BEFORE_CONFIG | OPT_INTERNAL | OPT_NO_VALUE, "\tShow this help")
170
171 /** Boolean option. @target should be a variable of type `int`. **/
172 #define OPT_BOOL(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, int *), .help = desc, .flags = fl, .cls = OPT_CL_BOOL, .type = CT_INT }
173
174 /** String option. @target should be a variable of type `char *`. **/
175 #define OPT_STRING(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, char **), .help = desc, .flags = fl, .cls = OPT_CL_STATIC, .type = CT_STRING }
176
177 /** Ordinary integer option. @target should be a variable of type `int`. **/
178 #define OPT_INT(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, int *), .help = desc, .flags = fl, .cls = OPT_CL_STATIC, .type = CT_INT }
179
180 /** Unsigned integer option. @target should be a variable of type `uint`. **/
181 #define OPT_UINT(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, uint *), .help = desc, .flags = fl, .cls = OPT_CL_STATIC, .type = CT_INT }
182
183 /** 64-bit integer option. @target should be a variable of type `u64`. **/
184 #define OPT_U64(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, u64 *), .help = desc, .flags = fl, .cls = OPT_CL_STATIC, .type = CT_U64 }
185
186 /** Floating-point option. @target should be a variable of type `double`. **/
187 #define OPT_DOUBLE(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, double *), .help = desc, .flags = fl, .cls = OPT_CL_STATIC, .type = CT_DOUBLE }
188
189 /** IP address option, currently IPv4 only. @target should be a variable of type `u32`. **/
190 #define OPT_IP(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, u32 *), .help = desc, .flags = fl, .cls = OPT_CL_STATIC, .type = CT_IP }
191
192 /** Multi-valued string option. @target should be a growing array of `char *`s. **/
193 #define OPT_STRING_MULTIPLE(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, char ***), .help = desc, .flags = fl, .cls = OPT_CL_MULTIPLE, .type = CT_STRING }
194
195 /** Multi-valued integer option. @target should be a growing array of `int`s. **/
196 #define OPT_INT_MULTIPLE(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, int **), .help = desc, .flags = fl, .cls = OPT_CL_MULTIPLE, .type = CT_INT }
197
198 /** Multi-valued unsigned integer option. @target should be a growing array of `uint`s. **/
199 #define OPT_UINT_MULTIPLE(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, uint **), .help = desc, .flags = fl, .cls = OPT_CL_MULTIPLE, .type = CT_INT }
200
201 /** Multi-valued 64-bit integer option. @target should be a growing array of `u64`s. **/
202 #define OPT_U64_MULTIPLE(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, u64 **), .help = desc, .flags = fl, .cls = OPT_CL_MULTIPLE, .type = CT_U64 }
203
204 /** Multi-valued floating-point option. @target should be a growing array of `double`s. **/
205 #define OPT_DOUBLE_MULTIPLE(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, double **), .help = desc, .flags = fl, .cls = OPT_CL_MULTIPLE, .type = CT_DOUBLE }
206
207 /** Multi-valued IPv4 address option. @target should be a growing array of `u32`s. **/
208 #define OPT_IP_MULTIPLE(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, u32 **), .help = desc, .flags = fl, .cls = OPT_CL_MULTIPLE, .type = CT_IP }
209
210 /** Switch option. @target should be a variable of type `int` and it will be set to the value @val. **/
211 #define OPT_SWITCH(shortopt, longopt, target, val, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, int *), .help = desc, .flags = fl, .cls = OPT_CL_SWITCH, .type = CT_LOOKUP, .u.value = val }
212
213 /** Incrementing option. @target should be a variable of type `int`. **/
214 #define OPT_INC(shortopt, longopt, target, fl, desc) { .letter = shortopt, .name = longopt, .ptr = CHECK_PTR_TYPE(&target, int *), .flags = fl, .help = desc, .cls = OPT_CL_INC, .type = CT_INT }
215
216 /** Breakpoint option. When this option occurs, parsing is terminated and the option is kept in the argument array. **/
217 #define OPT_BREAK(shortopt, longopt, fl) { .letter = shortopt, .name = longopt, .flags = fl, .cls = OPT_CL_BREAK }
218
219 /* FIXME: Backwards compatibility only, should not be used anymore. */
220 #define OPT_UNS OPT_UINT
221 #define OPT_UNS_MULTIPLE OPT_UINT_MULTIPLE
222
223
224 /**
225  * When this option appears, call the function @fn with parameters @item, @value, @data,
226  * where @item points to the <<struct_opt_item,`struct opt_item`>> of this option,
227  * @value contains the current argument of the option (NULL if there is none),
228  * and @data is specified here.
229  **/
230 #define OPT_CALL(shortopt, longopt, fn, data, fl, desc) { .letter = shortopt, .name = longopt, .ptr = data, .help = desc, .u.call = fn, .flags = fl, .cls = OPT_CL_CALL, .type = CT_USER }
231
232 /**
233  * An option with user-defined syntax. @ttype is a <<conf:struct_cf_user_type,`cf_user_type`>>
234  * describing the syntax, @target is a variable of the corresponding type. If the @OPT_REQUIRED_VALUE
235  * flag is not set, the parser must be able to parse a NULL value.
236  **/
237 #define OPT_USER(shortopt, longopt, target, ttype, fl, desc) { .letter = shortopt, .name = longopt, .ptr = &target, .u.utype = &ttype, .flags = fl, .help = desc, .cls = OPT_CL_STATIC, .type = CT_USER }
238
239 /** Multi-valued option of user-defined type. @target should be a growing array of the right kind of items. **/
240 #define OPT_USER_MULTIPLE(shortopt, longopt, target, ttype, fl, desc) { .letter = shortopt, .name = longopt, .ptr = &target, .u.utype = &ttype, .flags = fl, .help = desc, .cls = OPT_CL_MULTIPLE, .type = CT_USER }
241
242 /** A sub-section. **/
243 #define OPT_SECTION(sec) { .cls = OPT_CL_SECTION, .u.section = &sec }
244
245 /** Declares a <<hooks,hook>> to call upon any event from the specified set. **/
246 #define OPT_HOOK(fn, data, events) { .cls = OPT_CL_HOOK, .u.hook = fn, .flags = events, .ptr = data }
247
248 /** A terminator signalling the end of the option list. **/
249 #define OPT_END { .cls = OPT_CL_END }
250
251 /***
252  * [[positional]]
253  * Positional arguments
254  * --------------------
255  *
256  * In addition to short and long options, the parser can also process 'positional
257  * arguments', which don't start with a dash and whose meaning depends solely on
258  * their position.
259  *
260  * Positional arguments are declared as options with short name `OPT_POSITIONAL(n)`
261  * (where `n` is the position of the argument, starting with 1) and long name
262  * NULL. To accept an arbitrary number of positional arguments, use
263  * `OPT_POSITIONAL_TAIL` instead, which matches all arguments, for which no
264  * `OPT_POSITIONAL` is defined. (In the latter case, you probably want to define
265  * the argument as `OPT_MULTIPLE` or `OPT_CALL`, so that the values do not
266  * overwrite each other.)
267  *
268  * Options and positional arguments can be mixed arbitrarily. When a `--` appears
269  * as an argument, it is understood as a signal that all other arguments are
270  * positional.
271  *
272  * `OPT_REQUIRED` can be used with positional arguments, but all required arguments
273  * must come before the non-required ones. When `OPT_POSITIONAL_TAIL` is declared
274  * required, it means that it must match at least once.
275  *
276  * Ordering of positional arguments within the list of options need not match
277  * their positions. Holes in position numbering are inadvisable.
278  ***/
279
280 #define OPT_POSITIONAL(n)   (OPT_POSITIONAL_TAIL+(n))
281 #define OPT_POSITIONAL_TAIL 128
282
283 /***
284  * [[func]]
285  * Functions
286  * ---------
287  ***/
288
289 /**
290  * Parse all arguments, given in a NULL-terminated array of strings.
291  *
292  * Typically, this is called from `main(argc, argv)` as `opt_parse(options, argv+1)`,
293  * skipping the 0th argument, which contains program name.
294  *
295  * Returns the number of arguments used (which need not be all of them
296  * if `OPT_LAST_ARG` was encountered).
297  *
298  * The argument array is left untouched.
299  * However, option values are not necessarily copied, the variables
300  * set by the parser may point to the argument array.
301  **/
302 int opt_parse(const struct opt_section * options, char ** argv);
303
304 /**
305  * Report parsing failure, suggest `--help`, and abort the program with
306  * exit code 2.
307  **/
308 void opt_failure(const char * mesg, ...) FORMAT_CHECK(printf,1,2) NONRET;
309
310 void opt_help(const struct opt_section * sec);
311 void opt_handle_help(const struct opt_item * opt, const char * value, void * data);
312
313 /***
314  * [[conf]]
315  * Cooperating with config file parser
316  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
317  *
318  * Parsing of command-line options and configuration files are usually
319  * intertwined in a somewhat tricky way. We want to provide command-line
320  * options that control the name of the configuration file, or possibly to
321  * override configuration settings from the command line. On the other hand,
322  * regular command-line options can refer to values loaded from the
323  * program's configuration.
324  *
325  * To achieve this goal, the option parser is able to cooperate with the
326  * config file parser. This is enabled by listing the `OPT_CONF_OPTIONS`
327  * macro in the list of command-line options.
328  *
329  * The following options are defined for you:
330  *
331  * - `-C` (`--config`) to load a specific configuration file. This option
332  *   suppresses loading of the default configuration, but it can be given
333  *   multiple times to merge settings from several files.
334  *
335  * - `-S` (`--set`) to include a part of configuration inline. For example,
336  *   you can use `-Ssection.item=value` to change a single configuration item.
337  *
338  * - `--dumpconfig` to dump the configuration to standard output and exit.
339  *   (This is available only if the program is compiled with `CONFIG_UCW_DEBUG`.)
340  *
341  * The default configuration file (as specified by <<var_cf_def_file,`cf_def_file`>>) is loaded
342  * as soon as the first option different from `-C` is encountered, unless
343  * a different file has been already loaded. For this reason, `-C` must be
344  * the very first argument given to the program.
345  *
346  * This interface supersedes <<conf:getopt_h,`cf_getopt()`>>.
347  ***/
348
349 #ifdef CONFIG_UCW_DEBUG
350 #define OPT_CONF_OPTIONS    OPT_CONF_CONFIG, OPT_CONF_SET, OPT_CONF_DUMPCONFIG, OPT_CONF_HOOK
351 #else
352 #define OPT_CONF_OPTIONS    OPT_CONF_CONFIG, OPT_CONF_SET, OPT_CONF_HOOK
353 #endif
354
355 #define OPT_CONF_CONFIG     OPT_CALL('C', "config", opt_handle_config, NULL, OPT_BEFORE_CONFIG | OPT_INTERNAL | OPT_REQUIRED_VALUE, "<file>\tOverride the default configuration file")
356 #define OPT_CONF_SET        OPT_CALL('S', "set", opt_handle_set, NULL, OPT_BEFORE_CONFIG | OPT_INTERNAL | OPT_REQUIRED_VALUE, "<item>\tManual setting of a configuration item")
357 #define OPT_CONF_DUMPCONFIG OPT_CALL(0, "dumpconfig", opt_handle_dumpconfig, NULL, OPT_INTERNAL | OPT_NO_VALUE, "\tDump program configuration")
358 #define OPT_CONF_HOOK       OPT_HOOK(opt_conf_hook_internal, NULL, OPT_HOOK_BEFORE_VALUE | OPT_HOOK_FINAL | OPT_HOOK_INTERNAL)
359
360 void opt_handle_config(const struct opt_item * opt, const char * value, void * data);
361 void opt_handle_set(const struct opt_item * opt, const char * value, void * data);
362 void opt_handle_dumpconfig(const struct opt_item * opt, const char * value, void * data);
363 void opt_conf_hook_internal(const struct opt_item * opt, uint event, const char * value, void * data);
364
365 // XXX: This is duplicated with <ucw/getopt.h>, but that one will hopefully go away one day.
366 /**
367  * The name of the default configuration file (NULL if configuration has been
368  * already loaded). It is initialized to `CONFIG_UCW_DEFAULT_CONFIG`, but you
369  * usually want to replace it by your own config file.
370  */
371 extern char *cf_def_file;
372 /**
373  * Name of environment variable that can override what configuration is loaded.
374  * Defaults to the value of the `CONFIG_UCW_ENV_VAR_CONFIG` compile-time option.
375  **/
376 extern char *cf_env_file;
377
378 /***
379  * [[hooks]]
380  * Hooks
381  * -----
382  *
383  * You can supply hook functions, which will be called by the parser upon various
384  * events. Hooks are declared as option items of class `OPT_CL_HOOK`, whose @flags
385  * field specifies a mask of events the hook wants to receive.
386  *
387  * Please note that the hook interface is not considered stable yet,
388  * so it might change in future versions of libucw.
389  *
390  * The following events are defined:
391  ***/
392
393 #define OPT_HOOK_BEFORE_ARG     0x1     /** Call before option parsing **/
394 #define OPT_HOOK_BEFORE_VALUE   0x2     /** Call before value parsing **/
395 #define OPT_HOOK_AFTER_VALUE    0x4     /** Call after value parsing **/
396 #define OPT_HOOK_FINAL          0x8     /** Call just before @opt_parse() returns **/
397 #define OPT_HOOK_INTERNAL       0x4000  // Used internally to ask for passing of struct opt_context
398
399 #endif