From 6c49c299b953297cd9a60a0b2aeaa6b42f1faeab Mon Sep 17 00:00:00 2001 From: Philip Top Date: Mon, 20 Sep 2021 07:23:39 -0700 Subject: [PATCH] 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 Co-authored-by: Henry Schreiner --- README.md | 23 +++++++----- book/chapters/options.md | 14 +++++--- include/CLI/App.hpp | 9 +++-- include/CLI/Option.hpp | 34 ++++++++++++++---- tests/AppTest.cpp | 29 ++++++++++++++++ tests/OptionTypeTest.cpp | 75 ++++++++++++++++++++++++++++++++++++++-- 6 files changed, 161 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 8c3f3a777..164b1431e 100644 --- a/README.md +++ b/README.md @@ -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). @@ -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. @@ -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` of results. @@ -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()`: 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()`: 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 diff --git a/book/chapters/options.md b/book/chapters/options.md index 299f4a4e8..8b1daa0ff 100644 --- a/book/chapters/options.md +++ b/book/chapters/options.md @@ -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" | @@ -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 | @@ -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. diff --git a/include/CLI/App.hpp b/include/CLI/App.hpp index ed853c0b7..03b58d9fe 100644 --- a/include/CLI/App.hpp +++ b/include/CLI/App.hpp @@ -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(); } } @@ -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 @@ -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); diff --git a/include/CLI/Option.hpp b/include/CLI/Option.hpp index 5e0028aab..616cd120c 100644 --- a/include/CLI/Option.hpp +++ b/include/CLI/Option.hpp @@ -340,6 +340,10 @@ class Option : public OptionBase