diff --git a/README.md b/README.md index 0e8c77f50..eb8d4b57a 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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)`. @@ -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. diff --git a/book/chapters/config.md b/book/chapters/config.md index 79295bdbf..5f492833e 100644 --- a/book/chapters/config.md +++ b/book/chapters/config.md @@ -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 diff --git a/include/CLI/Validators.hpp b/include/CLI/Validators.hpp index 63422cb7a..4be8bb349 100644 --- a/include/CLI/Validators.hpp +++ b/include/CLI/Validators.hpp @@ -462,6 +462,34 @@ template class TypeValidator : public Validator { /// Check for a number const TypeValidator 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: diff --git a/tests/ConfigFileTest.cpp b/tests/ConfigFileTest.cpp index 658aae083..ac62a3e20 100644 --- a/tests/ConfigFileTest.cpp +++ b/tests/ConfigFileTest.cpp @@ -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() == "../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() == "../TestIniTmp.ini"); +} + TEST_CASE_METHOD(TApp, "IniPositional", "[config]") { TempFile tmpini{"TestIniTmp.ini"}; diff --git a/tests/HelpersTest.cpp b/tests/HelpersTest.cpp index 7a497aa1c..9985cc85a 100644 --- a/tests/HelpersTest.cpp +++ b/tests/HelpersTest.cpp @@ -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(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));