Skip to content

Commit

Permalink
feat: add a more clear force callback (#631)
Browse files Browse the repository at this point in the history
* 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]>
  • Loading branch information
4 people authored Sep 20, 2021
1 parent bd3c9cb commit 6c49c29
Show file tree
Hide file tree
Showing 6 changed files with 161 additions and 23 deletions.
23 changes: 14 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -336,10 +336,12 @@ Before parsing, you can set the following options:

* `->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.
* `->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.
* `->expected(MIN,MAX)`: Set a range of expected values to accompany an option. `expected(0,1)` is the equivalent of making a flag.
* `->type_name(typename)`: Set the name of an Option's type (`type_name_fn` allows a function instead)
* `->type_size(N)`: Set the intrinsic size of an option. The parser will require multiples of this number if negative.
* `->needs(opt)`: This option requires another option to also be present, opt is an `Option` pointer.
* `->excludes(opt)`: This option cannot be given with `opt` present, opt is an `Option` pointer.
* `->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.
* `->type_size(MIN,MAX)`: Set the intrinsic size of an option to a range.
* `->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
* `->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)`
* `->envname(name)`: Gets the value from the environment if present and not passed on the command line.
* `->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).
* `->ignore_case()`: Ignore the case on the command line (also works on subcommands, does not affect arguments).
Expand All @@ -348,7 +350,7 @@ Before parsing, you can set the following options:
* `->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.
* `->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.
* `->description(str)`: Set/change the description.
* `->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).
* `->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()`
* `->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
* `->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.
* `->transform(std::string(std::string &), validator_name="",validator_description=")`: Converts the input string into the output string, in-place in the parsed options.
Expand All @@ -358,9 +360,12 @@ Before parsing, you can set the following options:
* `->capture_default_str()`: Store the current value attached and display it in the help string.
* `->default_function(std::string())`: Advanced: Change the function that `capture_default_str()` uses.
* `->always_capture_default()`: Always run `capture_default_str()` when creating new options. Only useful on an App's `option_defaults`.
* `->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.
* `->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).
* `->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.
* `->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.
* `->run_callback_for_default()`: This will force the option callback to be executed or the variable set when the default_val is set.
* `->option_text(string)`: Sets the text between the option name and description.
* `->force_callback()`: Causes the option callback or value set to be triggered even if the option was not present in parsing.
* `->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.

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.

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

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:

* `results()`: Retrieves a vector of strings with all the results in the order they were given.
* `results(variable_to_bind_to)`: Gets the results according to the MultiOptionPolicy and converts them just like the `add_option_function` with a variable.
* `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.
* `->results()`: Retrieves a vector of strings with all the results in the order they were given.
* `->results(variable_to_bind_to)`: Gets the results according to the MultiOptionPolicy and converts them just like the `add_option_function` with a variable.
* `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.

### Subcommands

Expand Down
14 changes: 10 additions & 4 deletions book/chapters/options.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ You can use any C++ int-like type, not just `int`. CLI11 understands the followi

| Type | CLI11 |
|-------------|-------|
| number like | Integers, floats, bools, or any type that can be constructed from an integer or floating point number |
| 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 |
| string-like | std\::string, or anything that can be constructed from or assigned a std\::string |
| char | For a single char, single string values are accepted, otherwise longer strings are treated as integral values and a conversion is attempted |
| 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" |
Expand Down Expand Up @@ -129,8 +129,8 @@ When you call `add_option`, you get a pointer to the added option. You can use t
| `->expected(Nmin,Nmax)` | Take between `Nmin` and `Nmax` values. |
| `->type_size(N)` | specify that each block of values would consist of N elements |
| `->type_size(Nmin,Nmax)` | specify that each block of values would consist of between Nmin and Nmax elements |
| `->needs(opt)` | This option requires another option to also be present, opt is an `Option` pointer. |
| `->excludes(opt)` | This option cannot be given with `opt` present, opt is an `Option` pointer. |
| `->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)` |
| `->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)` |
| `->envname(name)` | Gets the value from the environment if present and not passed on the command line. |
| `->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. |
| `->description(string)` | Set/change the description |
Expand All @@ -149,8 +149,14 @@ When you call `add_option`, you get a pointer to the added option. You can use t
| `->transform(Validator)` | Run a transforming validator on each value passed. See [Validators](./validators.md) for more info |
| `->each(void(std::string))` | Run a function on each parsed value, *in order*. |
| `->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 |
| `->default_function(string())` | Advanced: Change the function that `capture_default_str()` uses. |
| `->default_function(std::string())` | Advanced: Change the function that `capture_default_str()` uses. |
| `->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). |
| `->capture_default_str()` | Store the current value attached and display it in the help string. |
| `->always_capture_default()` | Always run `capture_default_str()` when creating new options. Only useful on an App's `option_defaults`. |
| `->run_callback_for_default()` | Force the option callback to be executed or the variable set when the `default_val` is used. |
| `->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 |
|`->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|
| `->option_text(string)` | Sets the text between the option name and description. |

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.

Expand Down
9 changes: 7 additions & 2 deletions include/CLI/App.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2082,7 +2082,7 @@ class App {
}

for(const Option_p &opt : options_) {
if(opt->count() > 0 && !opt->get_callback_run()) {
if((*opt) && !opt->get_callback_run()) {
opt->run_callback();
}
}
Expand Down Expand Up @@ -2754,6 +2754,9 @@ class App {
op->add_result(std::string{});
}
}
if(op->get_trigger_on_parse() && op->current_option_state_ == Option::option_state::callback_run) {
op->clear();
}
int min_num = (std::min)(op->get_type_size_min(), op->get_items_expected_min());
int max_num = op->get_items_expected_max();
// check container like options to limit the argument size to a single type if the allow_extra_flags argument is
Expand Down Expand Up @@ -2826,7 +2829,9 @@ class App {
if(min_num > 0 && op->get_type_size_max() != min_num && (collected % op->get_type_size_max()) != 0) {
op->add_result(std::string{});
}

if(op->get_trigger_on_parse()) {
op->run_callback();
}
if(!rest.empty()) {
rest = "-" + rest;
args.push_back(rest);
Expand Down
34 changes: 28 additions & 6 deletions include/CLI/Option.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,10 @@ class Option : public OptionBase<Option> {
bool run_callback_for_default_{false};
/// flag indicating a separator needs to be injected after each argument call
bool inject_separator_{false};
/// flag indicating that the option should trigger the validation and callback chain on each result when loaded
bool trigger_on_result_{false};
/// flag indicating that the option should force the callback regardless if any results present
bool force_callback_{false};
///@}

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

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

/// Clear the parsed results (mostly for testing)
void clear() {
Expand Down Expand Up @@ -423,6 +427,21 @@ class Option : public OptionBase<Option> {
}
/// Get the current value of allow extra args
bool get_allow_extra_args() const { return allow_extra_args_; }
/// Set the value of trigger_on_parse which specifies that the option callback should be triggered on every parse
Option *trigger_on_parse(bool value = true) {
trigger_on_result_ = value;
return this;
}
/// The status of trigger on parse
bool get_trigger_on_parse() const { return trigger_on_result_; }

/// Set the value of force_callback
Option *force_callback(bool value = true) {
force_callback_ = value;
return this;
}
/// The status of force_callback
bool get_force_callback() const { return force_callback_; }

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

/// The number of arguments the option expects
/// Return the inject_separator flag
int get_inject_separator() const { return inject_separator_; }

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

/// Process the callback
void run_callback() {

if(force_callback_ && results_.empty()) {
add_result(default_str_);
}
if(current_option_state_ == option_state::parsing) {
_validate_results(results_);
current_option_state_ = option_state::validated;
Expand Down Expand Up @@ -977,10 +998,10 @@ class Option : public OptionBase<Option> {

/// Puts a result at the end
Option *add_result(std::vector<std::string> s) {
current_option_state_ = option_state::parsing;
for(auto &str : s) {
_add_result(std::move(str), results_);
}
current_option_state_ = option_state::parsing;
return this;
}

Expand Down Expand Up @@ -1139,7 +1160,8 @@ class Option : public OptionBase<Option> {
results_.clear();
try {
add_result(val_str);
if(run_callback_for_default_) {
// if trigger_on_result_ is set the callback already ran
if(run_callback_for_default_ && !trigger_on_result_) {
run_callback(); // run callback sets the state we need to reset it again
current_option_state_ = option_state::parsing;
} else {
Expand Down
29 changes: 29 additions & 0 deletions tests/AppTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2279,3 +2279,32 @@ TEST_CASE_METHOD(TApp, "CustomUserSepParse5", "[app]") {
run();
CHECK(std::vector<std::string>({"this", "is", "a", "test"}) == bar);
}

// #218
TEST_CASE_METHOD(TApp, "logFormSingleDash", "[app]") {
bool verbose{false};
bool veryverbose{false};
bool veryveryverbose{false};
app.name("testargs");
app.allow_extras();
args = {"-v", "-vv", "-vvv"};
app.final_callback([&]() {
auto rem = app.remaining();
for(auto &arg : rem) {
if(arg == "-v") {
verbose = true;
}
if(arg == "-vv") {
veryverbose = true;
}
if(arg == "-vvv") {
veryveryverbose = true;
}
}
});
run();
CHECK(app.remaining().size() == 3U);
CHECK(verbose);
CHECK(veryverbose);
CHECK(veryveryverbose);
}
Loading

0 comments on commit 6c49c29

Please sign in to comment.