Skip to content

Commit

Permalink
add read and write file validators CLIUtils#249
Browse files Browse the repository at this point in the history
Signed-off-by: Rafi Wiener <[email protected]>
  • Loading branch information
Rafi Wiener committed Mar 4, 2019
1 parent be8a08f commit 3ab8954
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,8 @@ CLI11 has several Validators built in that perform some common checks
- `CLI::Transformer(...)`: 🚧 Modify the input using a map. See [Transforming Validators](#transforming-validators) for more details.
- `CLI::CheckedTransformer(...)`: 🚧 Modify the input using a map, and Require that the input is either in the set or already one of the outputs of the set. See [Transforming Validators](#transforming-validators) for more details.
- `CLI::ExistingFile`: Requires that the file exists if given.
- `CLI::ExistingReadFile`: Requires that the file given exists and have permission to read it.
- `CLI::ExistingWriteFile`: Requires that the file given exists and have permission to write to it.
- `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.
Expand Down
13 changes: 11 additions & 2 deletions include/CLI/Validators.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,8 @@ namespace detail {
/// Check for an existing file (returns error message if check fails)
class ExistingFileValidator : public Validator {
public:
ExistingFileValidator() : Validator("FILE") {
func_ = [](std::string &filename) {
ExistingFileValidator(unsigned short mode = 0) : Validator("FILE") {
func_ = [mode](std::string &filename) {
struct stat buffer;
bool exist = stat(filename.c_str(), &buffer) == 0;
bool is_dir = (buffer.st_mode & S_IFDIR) != 0;
Expand All @@ -226,6 +226,9 @@ class ExistingFileValidator : public Validator {
} else if(is_dir) {
return "File is actually a directory: " + filename;
}
if (mode && !(buffer.st_mode & mode)) {
return "File doesn't have the wanted permission: " + filename;
}
return std::string();
};
}
Expand Down Expand Up @@ -328,6 +331,12 @@ class PositiveNumber : public Validator {
/// Check for existing file (returns error message if check fails)
const detail::ExistingFileValidator ExistingFile;

/// Check that the file exist and available for read
const detail::ExistingFileValidator ExistingReadFile(S_IREAD);

/// Check that the file exist and available for write
const detail::ExistingFileValidator ExistingWriteFile(S_IWRITE);

/// Check for an existing directory (returns error message if check fails)
const detail::ExistingDirectoryValidator ExistingDirectory;

Expand Down

0 comments on commit 3ab8954

Please sign in to comment.