Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a transform/validator that checks for files on a default path. #698

Merged
merged 7 commits into from
Jan 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,7 @@ CLI11 has several Validators built-in that perform some common checks
* `CLI::ExistingDirectory`: Requires that the directory exists.
* `CLI::ExistingPath`: Requires that the path (file or directory) exists.
* `CLI::NonexistentPath`: Requires that the path does not exist.
* `CLI::FileOnDefaultPath`: 🚧 Best used as a transform, Will check that a file exists either directly or in a default path and update the path appropriately. See [Transforming Validators](#transforming-validators) for more details
* `CLI::Range(min,max)`: Requires that the option be between min and max (make sure to use floating point if needed). Min defaults to 0.
* `CLI::Bounded(min,max)`: Modify the input such that it is always between min and max (make sure to use floating point if needed). Min defaults to 0. Will produce an error if conversion is not possible.
* `CLI::PositiveNumber`: Requires the number be greater than 0
Expand Down Expand Up @@ -484,6 +485,8 @@ of `Transformer`:

NOTES: If the container used in `IsMember`, `Transformer`, or `CheckedTransformer` has a `find` function like `std::unordered_map` or `std::map` then that function is used to do the searching. If it does not have a `find` function a linear search is performed. If there are filters present, the fast search is performed first, and if that fails a linear search with the filters on the key values is performed.

* `CLI::FileOnDefaultPath(default_path)`: 🚧 can be used to check for files in a default path. If used as a transform it will first check that a file exists, if it does nothing further is done, if it does not it tries to add a default Path to the file and search there again. If the file does not exist an error is returned normally but this can be disabled using CLI::FileOnDefaultPath(default_path, false). This allows multiple paths to be chained using multiple transform calls.

##### Validator operations

Validators are copyable and have a few operations that can be performed on them to alter settings. Most of the built in Validators have a default description that is displayed in the help. This can be altered via `.description(validator_description)`.
Expand Down Expand Up @@ -795,6 +798,14 @@ app.set_config("--config")->expected(1, X);

Where X is some positive number and will allow up to `X` configuration files to be specified by separate `--config` arguments. Value strings with quote characters in it will be printed with a single quote. All other arguments will use double quote. Empty strings will use a double quoted argument. Numerical or boolean values are not quoted.

NOTE: Transforms and checks can be used with the option pointer returned from set_config like any other option to validate the input if needed. It can also be used with the built in transform `CLI::FileOnDefaultPath` to look in a default path as well as the current one. For example

```cpp
app.set_config("--config")->transform(CLI::FileOnDefaultPath("/to/default/path/"));
```

See [Transforming Validators](#transforming-validators) for additional details on this validator. Multiple transforms or validators can be used either by multiple calls or using `|` operations with the transform.

### Inheriting defaults

Many of the defaults for subcommands and even options are inherited from their creators. The inherited default values for subcommands are `allow_extras`, `prefix_command`, `ignore_case`, `ignore_underscore`, `fallthrough`, `group`, `footer`,`immediate_callback` and maximum number of required subcommands. The help flag existence, name, and description are inherited, as well.
Expand Down
23 changes: 23 additions & 0 deletions book/chapters/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,29 @@

You can tell your app to allow configure files with `set_config("--config")`. There are arguments: the first is the option name. If empty, it will clear the config flag. The second item is the default file name. If that is specified, the config will try to read that file. The third item is the help string, with a reasonable default, and the final argument is a boolean (default: false) that indicates that the configuration file is required and an error will be thrown if the file is not found and this is set to true.

### Adding a default path

if it is desired that config files be searched for a in a default path the `CLI::FileOnDefaultPath` transform can be used.

```cpp
app.set_config("--config")->transform(CLI::FileOnDefaultPath("/default_path/"));
```

This will allow specified files to either exist as given or on a specified default path.

```cpp
app.set_config("--config")
->transform(CLI::FileOnDefaultPath("/default_path/"))
->transform(CLI::FileOnDefaultPath("/default_path2/",false));
```

Multiple default paths can be specified through this mechanism. The last transform given is executed first so the error return must be disabled so it can be chained to the first. The same effect can be achieved though the or(`|`) operation with validators

```cpp
app.set_config("--config")
->transform(CLI::FileOnDefaultPath("/default_path2/") | CLI::FileOnDefaultPath("/default_path/"));
```

### Extra fields

Sometimes configuration files are used for multiple purposes so CLI11 allows options on how to deal with extra fields
Expand Down
28 changes: 28 additions & 0 deletions include/CLI/Validators.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,34 @@ template <typename DesiredType> class TypeValidator : public Validator {
/// Check for a number
const TypeValidator<double> Number("NUMBER");

/// Modify a path if the file is a particular default location, can be used as Check or transform
/// with the error return optionally disabled
class FileOnDefaultPath : public Validator {
public:
explicit FileOnDefaultPath(std::string default_path, bool enableErrorReturn = true) : Validator("FILE") {
func_ = [default_path, enableErrorReturn](std::string &filename) {
auto path_result = detail::check_path(filename.c_str());
if(path_result == detail::path_type::nonexistent) {
std::string test_file_path = default_path;
if(default_path.back() != '/' && default_path.back() != '\\') {
// Add folder separator
test_file_path += '/';
}
test_file_path.append(filename);
path_result = detail::check_path(test_file_path.c_str());
if(path_result == detail::path_type::file) {
filename = test_file_path;
} else {
if(enableErrorReturn) {
return "File does not exist: " + filename;
}
}
}
return std::string{};
};
}
};

/// Produce a range (factory). Min and max are inclusive.
class Range : public Validator {
public:
Expand Down
58 changes: 58 additions & 0 deletions tests/ConfigFileTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1708,6 +1708,64 @@ TEST_CASE_METHOD(TApp, "IniShort", "[config]") {
CHECK(3 == key);
}

TEST_CASE_METHOD(TApp, "IniDefaultPath", "[config]") {

TempFile tmpini{"../TestIniTmp.ini"};

int key{0};
app.add_option("--flag,-f", key);
app.set_config("--config", "TestIniTmp.ini")->transform(CLI::FileOnDefaultPath("../"));

{
std::ofstream out{tmpini};
out << "f=3" << std::endl;
}

REQUIRE_NOTHROW(run());
CHECK(3 == key);
}

TEST_CASE_METHOD(TApp, "IniMultipleDefaultPath", "[config]") {

TempFile tmpini{"../TestIniTmp.ini"};

int key{0};
app.add_option("--flag,-f", key);
auto *cfgOption = app.set_config("--config", "doesnotexist.ini")
->transform(CLI::FileOnDefaultPath("../"))
->transform(CLI::FileOnDefaultPath("../other", false));

{
std::ofstream out{tmpini};
out << "f=3" << std::endl;
}

args = {"--config", "TestIniTmp.ini"};
REQUIRE_NOTHROW(run());
CHECK(3 == key);
CHECK(cfgOption->as<std::string>() == "../TestIniTmp.ini");
}

TEST_CASE_METHOD(TApp, "IniMultipleDefaultPathAlternate", "[config]") {

TempFile tmpini{"../TestIniTmp.ini"};

int key{0};
app.add_option("--flag,-f", key);
auto *cfgOption = app.set_config("--config", "doesnotexist.ini")
->transform(CLI::FileOnDefaultPath("../other") | CLI::FileOnDefaultPath("../"));

{
std::ofstream out{tmpini};
out << "f=3" << std::endl;
}

args = {"--config", "TestIniTmp.ini"};
REQUIRE_NOTHROW(run());
CHECK(3 == key);
CHECK(cfgOption->as<std::string>() == "../TestIniTmp.ini");
}

TEST_CASE_METHOD(TApp, "IniPositional", "[config]") {

TempFile tmpini{"TestIniTmp.ini"};
Expand Down
21 changes: 21 additions & 0 deletions tests/HelpersTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,27 @@ TEST_CASE("Validators: FileNotExists", "[helpers]") {
CHECK(CLI::NonexistentPath(myfile).empty());
}

TEST_CASE("Validators: FilePathModifier", "[helpers]") {
std::string myfile{"../TestFileNotUsed_1.txt"};
bool ok = static_cast<bool>(std::ofstream(myfile.c_str()).put('a')); // create file
CHECK(ok);
std::string filename = "TestFileNotUsed_1.txt";
CLI::FileOnDefaultPath defPath("../");
CHECK(defPath(filename).empty());
CHECK(filename == myfile);
std::string filename2 = "nonexistingfile.csv";
CHECK_FALSE(defPath(filename2).empty());
// check it didn't modify the string
CHECK(filename2 == "nonexistingfile.csv");
CHECK(defPath(filename).empty());
std::remove(myfile.c_str());
CHECK_FALSE(defPath(myfile).empty());
// now test the no error version
CLI::FileOnDefaultPath defPathNoFail("../", false);
CHECK(defPathNoFail(filename2).empty());
CHECK(filename2 == "nonexistingfile.csv");
}

TEST_CASE("Validators: FileIsDir", "[helpers]") {
std::string mydir{"../tests"};
CHECK("" != CLI::ExistingFile(mydir));
Expand Down