Commit 7868dc9f6cb226e7bf775ecf8b58bb7cd838c68c

Authored by Lucas Czech
1 parent 378eb340

Add path exists validator.

README.md
... ... @@ -179,6 +179,7 @@ The add commands return a pointer to an internally stored `Option`. If you set t
179 179 * `->multi_option_policy(CLI::MultiOptionPolicy::Throw)`: Set the multi-option policy. Shortcuts available: `->take_last()`, `->take_first()`, and `->join()`. This will only affect options expecting 1 argument or bool flags (which always default to take last).
180 180 * `->check(CLI::ExistingFile)`: Requires that the file exists if given.
181 181 * `->check(CLI::ExistingDirectory)`: Requires that the directory exists.
  182 +* `->check(CLI::ExistingPath)`: Requires that the path (file or directory) exists.
182 183 * `->check(CLI::NonexistentPath)`: Requires that the path does not exist.
183 184 * `->check(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.
184 185 * `->transform(std::string(std::string))`: Converts the input string into the output string, in-place in the parsed options.
... ...
include/CLI/Validators.hpp
... ... @@ -50,6 +50,16 @@ inline std::string ExistingDirectory(const std::string &filename) {
50 50 return std::string();
51 51 }
52 52  
  53 +/// Check for an existing path
  54 +inline std::string ExistingPath(const std::string &filename) {
  55 + struct stat buffer;
  56 + bool const exist = stat(filename.c_str(), &buffer) == 0;
  57 + if(!exist) {
  58 + return "Path does not exist: " + filename;
  59 + }
  60 + return std::string();
  61 +}
  62 +
53 63 /// Check for a non-existing path
54 64 inline std::string NonexistentPath(const std::string &filename) {
55 65 struct stat buffer;
... ...
tests/HelpersTest.cpp
... ... @@ -133,6 +133,27 @@ TEST(Validators, DirectoryIsFile) {
133 133 EXPECT_TRUE(CLI::NonexistentPath(myfile).empty());
134 134 }
135 135  
  136 +TEST(Validators, PathExistsDir) {
  137 + std::string mydir{"../tests"};
  138 + EXPECT_EQ(CLI::ExistingPath(mydir), "");
  139 +}
  140 +
  141 +TEST(Validators, PathExistsFile) {
  142 + std::string myfile{"TestFileNotUsed.txt"};
  143 + EXPECT_FALSE(CLI::ExistingPath(myfile).empty());
  144 + bool ok = static_cast<bool>(std::ofstream(myfile.c_str()).put('a')); // create file
  145 + EXPECT_TRUE(ok);
  146 + EXPECT_TRUE(CLI::ExistingPath(myfile).empty());
  147 +
  148 + std::remove(myfile.c_str());
  149 + EXPECT_FALSE(CLI::ExistingPath(myfile).empty());
  150 +}
  151 +
  152 +TEST(Validators, PathNotExistsDir) {
  153 + std::string mydir{"nonpath"};
  154 + EXPECT_NE(CLI::ExistingPath(mydir), "");
  155 +}
  156 +
136 157 // Yes, this is testing an app_helper :)
137 158 TEST(AppHelper, TempfileCreated) {
138 159 std::string name = "TestFileNotUsed.txt";
... ...