5 -----------------------------------------
6 An advanced command line options manager.
7 -----------------------------------------
9 :Author: Pierre Gentile p.gen.progs@gmail.com
17 **ctxopt** provides an advanced way to parse and evaluate complex command
18 line parameters and arguments.
20 Only two files **ctxopt.h** and **ctxopt.c** are needed to use **ctxopt**
26 The command line can be considered as a tree of contexts.
27 This offers the possibility of having a hierarchy of option groups.
29 Each option has a set of parameters which must start with a single dash
30 and may appear in the command line.
32 In order not to change habits, the double dash notation popularized by
33 the GNU **getopt_long** function for long options is also accepted and
34 automatically and silently converted to notation with a single dash.
36 These parameters are not limited to a dash followed by single letter.
37 In what follows, I will consider for simplicity that these are the options
38 which are visible in the command line and not one of their parameters.
40 Unless explicitly stated, the options are processed in the same order
41 as they appear in the command line, from left to right.
43 Any option may have the ability to modify the current context.
44 If such an option is seen in the command line, then the next option will
45 be looked for in this new context.
47 Initially the default context is the first created one in the program.
49 Exiting a context can be explicit, see below, or implicit if the current
50 option is not supported in this context.
51 The previous context in the hierarchy then becomes the current context
52 if it is not already the highest one.
54 An option which is unknown in the current context will be automatically
55 reevaluated in the previous one in the hierarchy.
56 If there is no such context, then a fatal error occurs.
58 A context can be explicitly delimited by a pair of symbols ``{`` and
60 The symbol ``{`` car appear just before or after the option responsible
61 of the context change.
63 The symbol ``}`` forces the end of a context.
65 The presence of ``{`` and ``}`` is purely optional and rarely necessary
66 but can help readability.
71 The API consists in the following functions:
73 * **void ctxopt_init(char *** \
79 This function initializes the internal structures uses by **ctxopt**.
80 It is mandatory and must me called first.
82 Its first argument (*prog_name*) is typically the content of ``argv[0]``
83 which nearly always contains the name of the program.
85 *prog_name* is used by the error system.
87 Its second argument (*flags*) will be read as a set of parameters
88 using the syntax ``flag=value``, each flag being separated from
89 its neighbor by spaces.
91 Flags may be missing in this argument, in this case the missing flags
92 will be given their default value which is given below.
93 An empty string is of course allowed but must be given anyway.
95 For now, only three flags are understood: **stop_if_non_option**,
96 **allow_abbreviations** and **display_usage_on_error**.
98 Their value can be **yes** or **no**, **1** and **0** and also accepted.
101 Instructs **ctxopt** to stop processing arguments as soon as it
102 encounters a non-option word in the command line, even if other
103 parameters remain to be processed. The default value of this flag
107 Tells **ctxopt** to try to guess a parameter name even if only its
108 beginning is given. The default value of this flag is **1** or
111 display_usage_on_error
112 If the setting is set to yes (default), the usage text for the
113 relevant contexts is displayed in case of a fatal error.
114 This may be useful to reduce the length of the error message and
115 allow the user to see the error more easily.
117 Example of content of the *flags* parameter:
121 "stop_if_non_option=1 allow_abbreviations=No"
125 * **void ctxopt_new_ctx(char *** \
131 The next thing to do after having called **ctxopt_new_ctx** is to
132 define the contexts and its associated options.
134 Using this function, you can name the new context and its authorized
135 options and determine their main characteristics with a syntax easy
137 If they already exist in another context, then they must have the same
138 signature (described below) as in their previous appearance.
140 *name* is the name of the new context and *opts_specs* must contain a
141 description of the options allowed in this context.
143 *opts_specs* is a string containing various components separated by
144 spaces according to the syntax below:
147 A mandatory option named opt without parameter usable only one type in
151 Two mandatory option named **opt1** and **opt2** without argument.
154 Same as above but can appear multiple time in the context.
157 Same as above but the option is optional
160 One mandatory and one optional option named **opt1** and **opt2**
161 without argument. **opt2** can appear multiple times in the context.
164 One mandatory option named **opt*** taking one mandatory argument.
167 One mandatory option named **opt** taking one mandatory argument.
168 **tag** is ignored but can be used to improve the readability.
171 One mandatory option named **opt** taking one optional argument.
174 One mandatory option named **opt** taking one or more mandatory
177 opt>ctx... [#<value>]
178 The mandatory multiple option named **opt** will switch to the
179 context named **cxt** which will become the new current context.
181 It takes an optional argument with a tag named **<value>**.
184 One optional option named **opt** taking multiple optional
187 The number of options/arguments allowed can be restricted by adding
188 an operator and an integer just after the dots like in the following
192 Here, the mandatory option **opt** is restricted to only appear
193 one or two times in the context.
194 The number of its mandatory arguments must be exactly three.
196 Valid operators are **<**, **=** and **>**.
198 The multiplicity or not of the options and argument, their mandatory or
199 optional characteristics constitutes their signatures.s
201 As said above, an option can appear in more than one context but must
202 have the same signature.
208 ctxopt_new_ctx("context1",
209 "[opt1>context2...] #arg1... [opt3]");
211 ctxopt_new_ctx("context2",
212 "[opt2 [#arg2]] [opt3]");
214 In the previous example, three options **opt1**, **opt2** and **opt3**
218 is mandatory and can appear more than one time and take multiple
222 is optional and take an optional argument.
225 is optional and take no argument.
226 Note that **opt3** is legal in both contexts.
230 **opt2**, if present in the command line, will be evaluated in the
231 context **context2**.
232 Note that, in this example, the **context2** can only be entered if
233 **opt1** has previously been seen in the command line.
234 Hence, **opt2** is only legal if **opt1** is present first.
236 **opt3** does not have this limitation.
237 In fact, as **opt3** is optional in **context2** and if its action
238 function is not interested in the name of the current context,
239 then it could have been omitted from the second setting thanks to
240 the backtracking: an option which is illegal in a context is retried
241 in the previous context in the hierarchy.
245 * **void ctxopt_ctx_disp_usage(char *** \
247 **, usage_behaviour** \
251 This function builds and prints an usage help text for the
252 specific context *ctx_name*.
253 The symbols used in this text are the same as those used when defining
254 options in **ctxopt_new_ctx**.
256 The parameter *action* can take the following values:
259 The program is not stopped when this function returns.
262 The program is stopped with a non zero return code (typically 1)
263 when this function returns.
265 The usage text is followed by a legend explaining the symbols meanings.
266 This function is useful when associated with a **help** or **usage**
271 * **void ctxopt_disp_usage(usage_behaviour** \
275 This function is similar to the preceding one but displays the usage
276 help text for all the defined contexts.
277 It is useful when associated with a general **help** or **usage**
280 The parameter *action* can take the following values:
283 The program is not stopped when this function returns.
286 The program is stopped with a non zero return code (typically 1)
287 when this function returns.
291 * **void ctxopt_add_global_settings(settings** \
297 This function allows to set general **ctxopt** settings.
298 As for now, the only possible setting for *s* is **error_functions**.
300 This setting tells **ctxopt_add_global_settings** to use the rest of
301 its arguments in order to replace the built-in error functions with
304 When the value of the first parameter is **error_functions**,
305 then the second one must be one of the following constants:
308 A mandatory parameter is missing.
311 A given parameter is unknown in the current context.
314 An option has been seen more than once but has not been declared as
315 multiple in the context.
318 An option is incompatible with an option already given in the context.
321 A mandatory argument is missing.
323 :CTXOPTCNTEOPT, CTXOPTCNTLOPT and CTXOPTCNTGOPT:
324 The number of occurrences is not equal, lower or greater than a
327 :CTXOPTCNTEARG, CTXOPTCNTLARG and CTXOPTCNTGARG:
328 The number of arguments of an option is not equal, lower or greater
331 and the third parameter is a function pointer with the following
336 void (*) (errors err, state_t * state);
338 *state* will point to the publicly available analysis state structure.
339 This structure contains a snapshot of variables related to the command
340 line analysis so far.
341 They and can be used to give the user clues about errors.
343 This structure available in **ctxopt.h** is:
349 char * prog_name; /* base name of the program name. */
350 char * ctx_name; /* current context name. */
351 char * ctx_par_name; /* parameter which led to this context. */
352 char * opt_name; /* current option name. */
353 char * opt_params; /* all parameters of the current option. */
354 int opts_count; /* limit of the number of occurrences of *
355 | the current option. */
356 int opt_args_count; /* limit of the number of parameters of *
357 | the current option. */
358 char * pre_opt_par_name; /* parameter just before the current one. */
359 char * cur_opt_par_name; /* current parameter. */
362 All these pointers can be equal to the **NULL** pointer.
368 ctxopt_add_global_settings(error_functions, CTXOPTMISPAR, error);
372 * **void ctxopt_add_ctx_settings(settings** \
378 This function manages some settings for a given context.
379 Its first parameter *s* determines the setting and the signification
380 of the remaining arguments.
382 Its possible values are:
385 This setting allows to declare a set of options incompatible with
388 In this case the second argument must be a context name and the
389 third argument must be a string containing option names separated
392 Example of **incompatibilities** setting:
396 void ctxopt_add_ctx_settings(incompatibilities,
400 The three options named **opt1**, **opt2** and **opt3** will be
401 marked as mutually incompatibles in each instance of the context
405 This setting allows options in a context to require the presence of
406 sets of other options of which at least one must be present.
407 Using this setting, the user can impose dependencies between options.
409 The option that imposes the requirement must be the first in the
410 list of options listed in the third arguments.
412 Example of **requirements** setting:
416 void ctxopt_add_ctx_settings(requirements;
420 At least one of the two options named **opt2** and **opt3** must
421 be present in the same context instance as **opt1** which is
422 **context1** in this case
424 There may be multiple requirements via multiple calls to
425 **ctxopt_add_ctx_settings** for the same first option (**opt1**
426 in the previous example) and the same context.
427 Each of them is considered in order.
430 This setting allows to associate a function to the context.
432 The second argument (called *f* below) will be called as soon as the
433 context is entered or exited during the evaluation phase.
435 Note that *f* will NOT be called if the context is empty
436 (does not contain any option).
438 The next parameters must be pointers to arbitrary data which may
441 In this setting, the last parameter must be **NULL**.
443 *f* must have the following prototype:
447 int (*) (char * name1, /* Context name */
448 direction status, /* entering or exiting */
449 char * name2, /* previous or next context */
450 int nb_data, /* Number of data */
451 void ** data /* Data */);
453 This function *f* will be called when entering **AND** exiting
455 Its arguments will then be set to:
458 the name of the context.
461 will be **entering** when entering the context and **exiting**
462 when exiting the context.
465 according to the content of *status*, the name of the context we
466 are coming from or the name of the context we are returning to.
468 *name2* can be **NULL** if we are entering in the main context or
472 The number of data pointers passed to the **ctxopt_add_ctx_settings**
473 function after the *s* parameter.
476 The data pointers passed to the **ctxopt_add_ctx_settings** function
477 after the *s* parameter and arranged in an array of *nb_data*
479 Example of **actions** setting:
483 void ctxopt_add_ctx_settings(actions,
486 &data_1, &data_2, &data_3,
489 This function call registers the **action** function to the context
492 The action function will be called **after** entering to and
493 **before** exiting from each instance of the context
496 The optional *data_X* pointers will be passed to **action** through
497 its data pointer to allow it to manipulate them if needed.
498 The count of these pointers (3 here) will also be passed to action
499 through its *nb_data* parameter.
501 The ending **NULL** is mandatory.
505 * **void ctxopt_add_opt_settings(settings** \
513 This function manages some settings for an option whose name is given in
516 The first parameter *s* determines the exact setting and the
517 signification of the remaining arguments.
518 Its possible values are:
521 This setting allows to associate command line parameters with *opt*.
522 The set of parameters must be given in the third argument as a string
523 containing words separated by blanks.
525 Each appearance of one of these parameters in the command line will
526 trigger the action associated with the named option.
528 Each of these words must start with one and exactly one dash.
530 Example of **parameters** setting:
534 ctxopt_add_opt_settings(parameters,
538 In this example, **opt1** is the name of a previously defined option and
539 **-p**, **-parm** and **-p1** will be three valid command line
540 parameters for the option **opt1**.
543 This setting allows to associate a function to this options.
544 As said above, this function will be called each time the option will be
545 recognized when evaluating the command line.
547 The function pointer must be given as the third argument.
549 Following the function pointer, it is possible to add a bunch of
550 other parameters which must be pointers to some pre-allocated arbitrary
553 These pointers will be passed to the function when called.
554 The last parameter must be **NULL** to end the sequence.
556 The function needs to be given as the third argument and must
557 match the following prototype:
561 void (*) (char * ctx_name, /* Context name */
562 char * opt_name, /* Option name */
563 char * param, /* Parameter name */
564 int nb_values, /* Number of arguments */
565 char ** values, /* Arguments */
566 int nb_opt_data, /* Number of option data passed */
567 void ** opt_data, /* Array of option data passed */
568 int nb_ctx_data, /* Number of context data passed */
569 void ** ctx_data /* Array of context data passed */)
572 is the name of the current context.
575 is the name of the option.
578 is the name of the parameter that triggered the option *opt_name*.
581 is the number of arguments immediately following this option in
585 is an array of stings containing the arguments following this
586 option in the command line.
589 is the number of data pointers which were given after the third
590 arguments of **ctxopt_add_opt_settings**.
593 The data pointers passed after the third arguments of
594 **ctxopt_add_opt_settings** and reorganized as an array of
595 *nb_opt_data* elements.
597 The aim is to be able to consult/alter options specific data.
600 Same as *nb_opt_data* but referencing to the number of data
601 pointers given to **ctxopt_add_ctx_settings** for the current
602 context after its third argument.
605 are the data pointers given to **ctxopt_add_ctx_settings** for the
606 current context after its third argument.
608 The aim is to be able to consult/alter contexts specific data.
610 Example of **actions** setting:
614 void action(char * ctx_name,
617 int nb_values, char ** values,
618 int nb_opt_data, void ** opt_data,
619 int nb_ctx_data, void ** ctx_data)
626 void ctxopt_add_opt_settings(actions, "opt1", action,
627 &data_1, &data_2, &data_3,
630 This example associates the function *action* to the option **opt1**.
632 Here, the *data_** pointers will be accessible to the function
633 *action* when called through its argument *opt_data* and their number
634 (3 here) through its argument *nb_opt_data* as mentioned above.
636 *action* will also have access to the current context data in the
637 same way through its arguments *ctx_data* and *nb_ctx_data*.
639 The *action* argument *param* will receive the value of the specific
640 parameter which triggered it - one of the parameters registered with
641 **ctxopt_add_opt_settings**.
644 This setting registers a function whose responsibility is to validate
645 that the arguments of the option respect some constraints.
647 To do that the third argument must be a function pointer and the fourth
648 argument must be some arbitrary parameter to this function needed
649 to validate the constraint.
651 The constraint function must match the following prototype:
655 int (*) (int nb_args, char ** args, char * value, char * parameter);
660 is the number which will be set to the number of arguments fol-
661 lowing the command line parameter.
664 is an array of nb_args strings containing theses arguments.
667 is an arbitrary string containing the constraints which must be
671 is the parameter of which *value* is an argument.
673 Three constraint functions are built-in and are described below.
674 They give examples on how to build them.
676 Example of constraint function using the built-it regular expression
677 constraint checker function:
681 ctxopt_add_opt_settings(constraints,
683 ctxopt_re_constraint,
687 In this example all the arguments of the option **opt1** must match
688 the extended regular expression::
692 See below for details about the function **ctxopt_re_constraint**.
695 These settings allow to tell ctxopt than some options must be
696 evaluated **before** or **after** a given option in a context.
697 This can be useful, for example, if an action triggered by the
698 evaluation of a option is required to be executed before the action
701 Example of **before** setting:
705 ctxopt_add_opt_settings(before,
709 In this example, **opt2** and **opt3** will be evaluated *before*
711 The relative order of **opt2** and **opt3** evaluations will still
712 follow their order of appearance in the command line.
714 Example of **after** setting:
718 ctxopt_add_opt_settings(after,
722 In this example, **opt3** and **opt4** will be evaluated *after*
724 This example shows than we can combine multiple settings reusing
725 options previously mentioned.
727 Incompatible setting combinations are not checked and will be ignored
728 or lead to undefined behaviors.
732 * **int ctxopt_format_constraint(int** \
742 This pre-defined constraint function checks whether the arguments
743 in *args* respect a C printf format given in value, `%2d` by e.g.
744 It returns 1 if the checking is successful and 0 if not.
748 * **int ctxopt_re_constraint(int** \
758 Another pre-defined constraint function which checks if the arguments
759 of an option respects the extended regular expression given in *value*.
761 It returns 1 if the arguments respects the constraint and 0 if this
766 * **int ctxopt_range_constraint(int** \
776 Yet another pre-defined constraint function. This one checks if the
777 arguments of an option are in in a specified ranges.
779 *value* must contain a string made of a maximum of 2 long integers
782 The first or the second of these numbers can be replaced with the
783 character '`.`'. In this case only the minimum or maximum is checked
784 and the '`.`' equals to plus or minus infinity depending of this
787 It returns 1 if the arguments respects the constraint and 0 if this
792 * **void ctxopt_analyze(int** \
802 This function processes the registered contexts instances tree, detects
803 errors and possibly reorganizes the options order according
806 The first two arguments are similar to the *argc* and *argv* arguments
807 of the main function but without counting `argv[0]`.
808 Therefore, in many cases, *nb_words* will have the value of `argc-1`
809 and *words* will have the value of `argv+1`.
811 The last two will receive the number of remaining (non analyzed)
812 command line words and the array of these remaining words.
813 Remaining words can be words appearing after ``--`` per example.
815 All errors are fatal and terminates the program with a return code
825 ctxopt_analyze(argc-1, argv+1, &res_argc, &res_argv);
829 * **void ctxopt_evaluate(void);**
831 This function walks through the tree of context instances previously
832 built by **ctxopt_analyze** and launches the action attached to
833 each options, if any, one after the other.
835 * **ctxopt_free_memory(void)**
837 This function frees the memory used internally by **ctxopt**.
842 **ctxopt** is able to switch to debug mode if the variable CTXOPT_DEBUG
843 is set to any not-empty value.
845 If this is the case, informational messages about how **ctxopt**
846 analyses the command line are printed on the error output.
848 Each of them are prefixed with "CTXOPT_DEBUG: ".