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