1
0
mirror of https://github.com/CLIUtils/CLI11.git synced 2025-05-01 13:13:53 +00:00

Adding check for Nonexistent

This commit is contained in:
Henry Fredrick Schreiner 2017-01-30 11:25:04 -05:00
parent fb16cb93fd
commit 3061782d3f
2 changed files with 40 additions and 2 deletions

View File

@ -115,8 +115,11 @@ bool _ExistingDirectory(std::string filename) {
}
bool _NonexistentPath(std::string filename) {
std::cout << "Validating: " << filename << std::endl;
struct stat buffer;
return stat(filename.c_str(), &buffer) != 0;
bool out = stat(filename.c_str(), &buffer) != 0;
std::cout << (out ? "Passed" : "Failed") << std::endl;
return out;
}
struct Error : public std::runtime_error {
@ -235,6 +238,12 @@ public:
/// Process the callback
bool run_callback() const {
if(opts.validators.size()>0) {
for(const std::string & result : flatten_results())
for(const std::function<bool(std::string)> &vali : opts.validators)
if(!vali(result))
return false;
}
return callback(results);
}
@ -315,6 +324,13 @@ public:
return out.str();
}
std::vector<std::string> flatten_results() const {
std::vector<std::string> output;
for(const std::vector<std::string> result : results)
output.insert(std::end(output), std::begin(result), std::end(result));
return output;
}
};

View File

@ -1,7 +1,7 @@
#include "CLI.hpp"
#include "gtest/gtest.h"
#include <fstream>
typedef std::vector<std::string> input_t;
@ -205,6 +205,28 @@ TEST_F(TApp, Reset) {
}
TEST_F(TApp, FileNotExists) {
std::string myfile{"TestNonFileNotUsed.txt"};
EXPECT_TRUE(CLI::_NonexistentPath(myfile));
std::string filename;
app.add_option("file", filename, "", CLI::NonexistentPath);
args = {"--file", myfile};
run();
EXPECT_EQ(myfile, filename);
app.reset();
bool ok = static_cast<bool>(std::ofstream(myfile.c_str()).put('a')); // create file
EXPECT_TRUE(ok);
EXPECT_THROW(run(), CLI::ParseError);
std::remove(myfile.c_str());
EXPECT_FALSE(CLI::_ExistingFile(myfile));
}
TEST_F(TApp, Basic) {
auto sub1 = app.add_subcommand("sub1");
auto sub2 = app.add_subcommand("sub2");