From 3061782d3ffcd9b49fa3c7ac1d33f5c2340fbd91 Mon Sep 17 00:00:00 2001 From: Henry Fredrick Schreiner Date: Mon, 30 Jan 2017 11:25:04 -0500 Subject: [PATCH] Adding check for Nonexistent --- include/CLI.hpp | 18 +++++++++++++++++- tests/CLITest.cpp | 24 +++++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/include/CLI.hpp b/include/CLI.hpp index 42dbbf84..9c3ee0e8 100644 --- a/include/CLI.hpp +++ b/include/CLI.hpp @@ -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 &vali : opts.validators) + if(!vali(result)) + return false; + } return callback(results); } @@ -315,6 +324,13 @@ public: return out.str(); } + std::vector flatten_results() const { + std::vector output; + for(const std::vector result : results) + output.insert(std::end(output), std::begin(result), std::end(result)); + return output; + } + }; diff --git a/tests/CLITest.cpp b/tests/CLITest.cpp index 44607586..a146222a 100644 --- a/tests/CLITest.cpp +++ b/tests/CLITest.cpp @@ -1,7 +1,7 @@ #include "CLI.hpp" #include "gtest/gtest.h" - +#include typedef std::vector 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(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");