Skip to content

Commit 6c49c29

Browse files
phlptppre-commit-ci[bot]henryiii
authored
feat: add a more clear force callback (#631)
* Add some missing modifiers on the options to the docs and clarify some of them. * style: pre-commit.ci fixes * add a more clear force callback and callback on parse modifier for options. * update the book with new modifiers * update documentation and add tests * style: pre-commit.ci fixes * more updates to the readme * update formatting * rework the trigger_on_parse to better support more complex option types * fix formatting errors * Update include/CLI/Option.hpp Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Henry Schreiner <[email protected]> Co-authored-by: Henry Schreiner <[email protected]>
1 parent bd3c9cb commit 6c49c29

File tree

6 files changed

+161
-23
lines changed

6 files changed

+161
-23
lines changed

README.md

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -336,10 +336,12 @@ Before parsing, you can set the following options:
336336

337337
* `->required()`: The program will quit if this option is not present. This is `mandatory` in Plumbum, but required options seems to be a more standard term. For compatibility, `->mandatory()` also works.
338338
* `->expected(N)`: Take `N` values instead of as many as possible, only for vector args. If negative, require at least `-N`; end with `--` or another recognized option or subcommand.
339+
* `->expected(MIN,MAX)`: Set a range of expected values to accompany an option. `expected(0,1)` is the equivalent of making a flag.
339340
* `->type_name(typename)`: Set the name of an Option's type (`type_name_fn` allows a function instead)
340-
* `->type_size(N)`: Set the intrinsic size of an option. The parser will require multiples of this number if negative.
341-
* `->needs(opt)`: This option requires another option to also be present, opt is an `Option` pointer.
342-
* `->excludes(opt)`: This option cannot be given with `opt` present, opt is an `Option` pointer.
341+
* `->type_size(N)`: Set the intrinsic size of an option value. The parser will require multiples of this number if negative. Most of the time this is detected automatically though can be modified for specific use cases.
342+
* `->type_size(MIN,MAX)`: Set the intrinsic size of an option to a range.
343+
* `->needs(opt)`: This option requires another option to also be present, opt is an `Option` pointer. Options can be removed from the `needs` with `remove_needs(opt)`. The option can also be specified with a string containing the name of the option
344+
* `->excludes(opt)`: This option cannot be given with `opt` present, opt is an `Option` pointer. Can also be given as a string containing the name of the option. Options can be removed from the excludes list with `->remove_excludes(opt)`
343345
* `->envname(name)`: Gets the value from the environment if present and not passed on the command line.
344346
* `->group(name)`: The help group to put the option in. No effect for positional options. Defaults to `"Options"`. `""` will not show up in the help print (hidden).
345347
* `->ignore_case()`: Ignore the case on the command line (also works on subcommands, does not affect arguments).
@@ -348,7 +350,7 @@ Before parsing, you can set the following options:
348350
* `->allow_extra_args(true/false)`: 🆕 If set to true the option will take an unlimited number of arguments like a vector, if false it will limit the number of arguments to the size of the type used in the option. Default value depends on the nature of the type use, containers default to true, others default to false.
349351
* `->delimiter(char)`: Allows specification of a custom delimiter for separating single arguments into vector arguments, for example specifying `->delimiter(',')` on an option would result in `--opt=1,2,3` producing 3 elements of a vector and the equivalent of --opt 1 2 3 assuming opt is a vector value.
350352
* `->description(str)`: Set/change the description.
351-
* `->multi_option_policy(CLI::MultiOptionPolicy::Throw)`: Set the multi-option policy. Shortcuts available: `->take_last()`, `->take_first()`,`->take_all()`, and `->join()`. This will only affect options expecting 1 argument or bool flags (which do not inherit their default but always start with a specific policy).
353+
* `->multi_option_policy(CLI::MultiOptionPolicy::Throw)`: Set the multi-option policy. Shortcuts available: `->take_last()`, `->take_first()`,`->take_all()`, and `->join()`. This will only affect options expecting 1 argument or bool flags (which do not inherit their default but always start with a specific policy). `->join(delim)` can also be used to join with a specific delimiter. This equivalent to calling `->delimiter(delim)` and `->join()`
352354
* `->check(std::string(const std::string &), validator_name="",validator_description="")`: Define a check function. The function should return a non empty string with the error message if the check fails
353355
* `->check(Validator)`: Use a Validator object to do the check see [Validators](#validators) for a description of available Validators and how to create new ones.
354356
* `->transform(std::string(std::string &), validator_name="",validator_description=")`: Converts the input string into the output string, in-place in the parsed options.
@@ -358,9 +360,12 @@ Before parsing, you can set the following options:
358360
* `->capture_default_str()`: Store the current value attached and display it in the help string.
359361
* `->default_function(std::string())`: Advanced: Change the function that `capture_default_str()` uses.
360362
* `->always_capture_default()`: Always run `capture_default_str()` when creating new options. Only useful on an App's `option_defaults`.
361-
* `->default_str(string)`: Set the default string directly. This string will also be used as a default value if no arguments are passed and the value is requested.
362-
* `->default_val(value)`: Generate the default string from a value and validate that the value is also valid. For options that assign directly to a value type the value in that type is also updated. Value must be convertible to a string(one of known types or have a stream operator).
363+
* `->default_str(string)`: Set the default string directly (NO VALIDATION OR CALLBACKS). This string will also be used as a default value if no arguments are passed and the value is requested.
364+
* `->default_val(value)`: Generate the default string from a value and validate that the value is also valid. For options that assign directly to a value type the value in that type is also updated. Value must be convertible to a string(one of known types or have a stream operator). The callback may be triggered if the `run_callback_for_default` is set.
365+
* `->run_callback_for_default()`: This will force the option callback to be executed or the variable set when the default_val is set.
363366
* `->option_text(string)`: Sets the text between the option name and description.
367+
* `->force_callback()`: Causes the option callback or value set to be triggered even if the option was not present in parsing.
368+
* `->trigger_on_parse()`: if set, causes the callback and all associated validation checks for the option to be executed when the option value is parsed vs. at the end of all parsing. This could cause the callback to be executed multiple times.
364369

365370
These options return the `Option` pointer, so you can chain them together, and even skip storing the pointer entirely. The `each` function takes any function that has the signature `void(const std::string&)`; it should throw a `ValidationError` when validation fails. The help message will have the name of the parent option prepended. Since `each`, `check` and `transform` use the same underlying mechanism, you can chain as many as you want, and they will be executed in order. Operations added through `transform` are executed first in reverse order of addition, and `check` and `each` are run following the transform functions in order of addition. If you just want to see the unconverted values, use `.results()` to get the `std::vector<std::string>` of results.
366371

@@ -536,9 +541,9 @@ Validators have a few functions to query the current values:
536541

537542
In most cases, the fastest and easiest way is to return the results through a callback or variable specified in one of the `add_*` functions. But there are situations where this is not possible or desired. For these cases the results may be obtained through one of the following functions. Please note that these functions will do any type conversions and processing during the call so should not used in performance critical code:
538543

539-
* `results()`: Retrieves a vector of strings with all the results in the order they were given.
540-
* `results(variable_to_bind_to)`: Gets the results according to the MultiOptionPolicy and converts them just like the `add_option_function` with a variable.
541-
* `Value=as<type>()`: Returns the result or default value directly as the specified type if possible, can be vector to return all results, and a non-vector to get the result according to the MultiOptionPolicy in place.
544+
* `->results()`: Retrieves a vector of strings with all the results in the order they were given.
545+
* `->results(variable_to_bind_to)`: Gets the results according to the MultiOptionPolicy and converts them just like the `add_option_function` with a variable.
546+
* `Value=opt->as<type>()`: Returns the result or default value directly as the specified type if possible, can be vector to return all results, and a non-vector to get the result according to the MultiOptionPolicy in place.
542547

543548
### Subcommands
544549

book/chapters/options.md

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ You can use any C++ int-like type, not just `int`. CLI11 understands the followi
2020

2121
| Type | CLI11 |
2222
|-------------|-------|
23-
| number like | Integers, floats, bools, or any type that can be constructed from an integer or floating point number |
23+
| number like | Integers, floats, bools, or any type that can be constructed from an integer or floating point number. Accepts common numerical strings like `0xFF` as well as octal, and decimal |
2424
| string-like | std\::string, or anything that can be constructed from or assigned a std\::string |
2525
| char | For a single char, single string values are accepted, otherwise longer strings are treated as integral values and a conversion is attempted |
2626
| complex-number | std::complex or any type which has a real(), and imag() operations available, will allow 1 or 2 string definitions like "1+2j" or two arguments "1","2" |
@@ -129,8 +129,8 @@ When you call `add_option`, you get a pointer to the added option. You can use t
129129
| `->expected(Nmin,Nmax)` | Take between `Nmin` and `Nmax` values. |
130130
| `->type_size(N)` | specify that each block of values would consist of N elements |
131131
| `->type_size(Nmin,Nmax)` | specify that each block of values would consist of between Nmin and Nmax elements |
132-
| `->needs(opt)` | This option requires another option to also be present, opt is an `Option` pointer. |
133-
| `->excludes(opt)` | This option cannot be given with `opt` present, opt is an `Option` pointer. |
132+
| `->needs(opt)` | This option requires another option to also be present, opt is an `Option` pointer or a string with the name of the option. Can be removed with `->remove_needs(opt)` |
133+
| `->excludes(opt)` | This option cannot be given with `opt` present, opt is an `Option` pointer or a string with the name of the option. Can be removed with `->remove_excludes(opt)` |
134134
| `->envname(name)` | Gets the value from the environment if present and not passed on the command line. |
135135
| `->group(name)` | The help group to put the option in. No effect for positional options. Defaults to `"Options"`. `"Hidden"` will not show up in the help print. |
136136
| `->description(string)` | Set/change the description |
@@ -149,8 +149,14 @@ When you call `add_option`, you get a pointer to the added option. You can use t
149149
| `->transform(Validator)` | Run a transforming validator on each value passed. See [Validators](./validators.md) for more info |
150150
| `->each(void(std::string))` | Run a function on each parsed value, *in order*. |
151151
| `->default_str(string)` | set a default string for use in the help and as a default value if no arguments are passed and a value is requested |
152-
| `->default_function(string())` | Advanced: Change the function that `capture_default_str()` uses. |
152+
| `->default_function(std::string())` | Advanced: Change the function that `capture_default_str()` uses. |
153153
| `->default_val(value)` | Generate the default string from a value and validate that the value is also valid. For options that assign directly to a value type the value in that type is also updated. Value must be convertible to a string(one of known types or have a stream operator). |
154+
| `->capture_default_str()` | Store the current value attached and display it in the help string. |
155+
| `->always_capture_default()` | Always run `capture_default_str()` when creating new options. Only useful on an App's `option_defaults`. |
156+
| `->run_callback_for_default()` | Force the option callback to be executed or the variable set when the `default_val` is used. |
157+
| `->force_callback()` | Force the option callback to be executed regardless of whether the option was used or not. Will use the default_str if available, if no default is given the callback will be executed with an empty string as an argument, which will translate to a default initialized value, which can be compiler dependent |
158+
|`->trigger_on_parse()` | Have the option callback be triggered when the value is parsed vs. at the end of all parsing, the option callback can potentially be executed multiple times. Generally only useful if you have a user defined callback or validation check. Or potentially if a vector input is given multiple times as it will clear the results when a repeat option is given via command line. It will trigger the callbacks once per option call on the command line|
159+
| `->option_text(string)` | Sets the text between the option name and description. |
154160

155161
The `->check(...)` and `->transform(...)` modifiers can also take a callback function of the form `bool function(std::string)` that runs on every value that the option receives, and returns a value that tells CLI11 whether the check passed or failed.
156162

include/CLI/App.hpp

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2082,7 +2082,7 @@ class App {
20822082
}
20832083

20842084
for(const Option_p &opt : options_) {
2085-
if(opt->count() > 0 && !opt->get_callback_run()) {
2085+
if((*opt) && !opt->get_callback_run()) {
20862086
opt->run_callback();
20872087
}
20882088
}
@@ -2754,6 +2754,9 @@ class App {
27542754
op->add_result(std::string{});
27552755
}
27562756
}
2757+
if(op->get_trigger_on_parse() && op->current_option_state_ == Option::option_state::callback_run) {
2758+
op->clear();
2759+
}
27572760
int min_num = (std::min)(op->get_type_size_min(), op->get_items_expected_min());
27582761
int max_num = op->get_items_expected_max();
27592762
// check container like options to limit the argument size to a single type if the allow_extra_flags argument is
@@ -2826,7 +2829,9 @@ class App {
28262829
if(min_num > 0 && op->get_type_size_max() != min_num && (collected % op->get_type_size_max()) != 0) {
28272830
op->add_result(std::string{});
28282831
}
2829-
2832+
if(op->get_trigger_on_parse()) {
2833+
op->run_callback();
2834+
}
28302835
if(!rest.empty()) {
28312836
rest = "-" + rest;
28322837
args.push_back(rest);

include/CLI/Option.hpp

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,10 @@ class Option : public OptionBase<Option> {
340340
bool run_callback_for_default_{false};
341341
/// flag indicating a separator needs to be injected after each argument call
342342
bool inject_separator_{false};
343+
/// flag indicating that the option should trigger the validation and callback chain on each result when loaded
344+
bool trigger_on_result_{false};
345+
/// flag indicating that the option should force the callback regardless if any results present
346+
bool force_callback_{false};
343347
///@}
344348

345349
/// Making an option by hand is not defined, it must be made by the App class
@@ -361,8 +365,8 @@ class Option : public OptionBase<Option> {
361365
/// True if the option was not passed
362366
bool empty() const { return results_.empty(); }
363367

364-
/// This class is true if option is passed.
365-
explicit operator bool() const { return !empty(); }
368+
/// This bool operator returns true if any arguments were passed or the option callback is forced
369+
explicit operator bool() const { return !empty() || force_callback_; }
366370

367371
/// Clear the parsed results (mostly for testing)
368372
void clear() {
@@ -423,6 +427,21 @@ class Option : public OptionBase<Option> {
423427
}
424428
/// Get the current value of allow extra args
425429
bool get_allow_extra_args() const { return allow_extra_args_; }
430+
/// Set the value of trigger_on_parse which specifies that the option callback should be triggered on every parse
431+
Option *trigger_on_parse(bool value = true) {
432+
trigger_on_result_ = value;
433+
return this;
434+
}
435+
/// The status of trigger on parse
436+
bool get_trigger_on_parse() const { return trigger_on_result_; }
437+
438+
/// Set the value of force_callback
439+
Option *force_callback(bool value = true) {
440+
force_callback_ = value;
441+
return this;
442+
}
443+
/// The status of force_callback
444+
bool get_force_callback() const { return force_callback_; }
426445

427446
/// Set the value of run_callback_for_default which controls whether the callback function should be called to set
428447
/// the default This is controlled automatically but could be manipulated by the user.
@@ -669,7 +688,7 @@ class Option : public OptionBase<Option> {
669688
/// The maximum number of arguments the option expects
670689
int get_type_size_max() const { return type_size_max_; }
671690

672-
/// The number of arguments the option expects
691+
/// Return the inject_separator flag
673692
int get_inject_separator() const { return inject_separator_; }
674693

675694
/// The environment variable associated to this value
@@ -821,7 +840,9 @@ class Option : public OptionBase<Option> {
821840

822841
/// Process the callback
823842
void run_callback() {
824-
843+
if(force_callback_ && results_.empty()) {
844+
add_result(default_str_);
845+
}
825846
if(current_option_state_ == option_state::parsing) {
826847
_validate_results(results_);
827848
current_option_state_ = option_state::validated;
@@ -977,10 +998,10 @@ class Option : public OptionBase<Option> {
977998

978999
/// Puts a result at the end
9791000
Option *add_result(std::vector<std::string> s) {
1001+
current_option_state_ = option_state::parsing;
9801002
for(auto &str : s) {
9811003
_add_result(std::move(str), results_);
9821004
}
983-
current_option_state_ = option_state::parsing;
9841005
return this;
9851006
}
9861007

@@ -1139,7 +1160,8 @@ class Option : public OptionBase<Option> {
11391160
results_.clear();
11401161
try {
11411162
add_result(val_str);
1142-
if(run_callback_for_default_) {
1163+
// if trigger_on_result_ is set the callback already ran
1164+
if(run_callback_for_default_ && !trigger_on_result_) {
11431165
run_callback(); // run callback sets the state we need to reset it again
11441166
current_option_state_ = option_state::parsing;
11451167
} else {

tests/AppTest.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2279,3 +2279,32 @@ TEST_CASE_METHOD(TApp, "CustomUserSepParse5", "[app]") {
22792279
run();
22802280
CHECK(std::vector<std::string>({"this", "is", "a", "test"}) == bar);
22812281
}
2282+
2283+
// #218
2284+
TEST_CASE_METHOD(TApp, "logFormSingleDash", "[app]") {
2285+
bool verbose{false};
2286+
bool veryverbose{false};
2287+
bool veryveryverbose{false};
2288+
app.name("testargs");
2289+
app.allow_extras();
2290+
args = {"-v", "-vv", "-vvv"};
2291+
app.final_callback([&]() {
2292+
auto rem = app.remaining();
2293+
for(auto &arg : rem) {
2294+
if(arg == "-v") {
2295+
verbose = true;
2296+
}
2297+
if(arg == "-vv") {
2298+
veryverbose = true;
2299+
}
2300+
if(arg == "-vvv") {
2301+
veryveryverbose = true;
2302+
}
2303+
}
2304+
});
2305+
run();
2306+
CHECK(app.remaining().size() == 3U);
2307+
CHECK(verbose);
2308+
CHECK(veryverbose);
2309+
CHECK(veryveryverbose);
2310+
}

0 commit comments

Comments
 (0)