SeqAn3  3.0.3
The Modern C++ library for sequence analysis.
validators.hpp
Go to the documentation of this file.
1 // -----------------------------------------------------------------------------------------------------
2 // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
3 // Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
4 // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
5 // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
6 // -----------------------------------------------------------------------------------------------------
7 
13 #pragma once
14 
15 #include <seqan3/std/algorithm>
16 #include <seqan3/std/concepts>
17 #include <seqan3/std/filesystem>
18 #include <fstream>
19 #include <seqan3/std/ranges>
20 #include <regex>
21 #include <sstream>
22 
34 
35 namespace seqan3
36 {
37 
95 template <typename validator_type>
96 SEQAN3_CONCEPT validator = std::copyable<std::remove_cvref_t<validator_type>> &&
97  requires(validator_type validator,
99 {
101 
102  SEQAN3_RETURN_TYPE_CONSTRAINT(validator(value), std::same_as, void);
104 };
106 
120 template <arithmetic option_value_t>
122 {
123 public:
125  using option_value_type = option_value_t;
126 
132  min{min_}, max{max_}
133  {}
134 
139  void operator()(option_value_type const & cmp) const
140  {
141  if (!((cmp <= max) && (cmp >= min)))
142  throw validation_error{detail::to_string("Value ", cmp, " is not in range [", min, ",", max, "].")};
143  }
144 
151  template <std::ranges::forward_range range_type>
155  void operator()(range_type const & range) const
156  {
157  std::for_each(range.begin(), range.end(), [&] (auto cmp) { (*this)(cmp); });
158  }
159 
162  {
163  return detail::to_string("Value must be in range [", min, ",", max, "].");
164  }
165 
166 private:
168  option_value_type min{};
169 
171  option_value_type max{};
172 };
173 
191 template <typename option_value_t>
193 {
194 public:
196  using option_value_type = option_value_t;
197 
201  value_list_validator() = default;
206  ~value_list_validator() = default;
207 
213  template <std::ranges::forward_range range_type>
215  requires std::constructible_from<option_value_type, std::ranges::range_rvalue_reference_t<range_type>>
217  value_list_validator(range_type rng)
218  {
219  values.clear();
220  std::ranges::move(std::move(rng), std::cpp20::back_inserter(values));
221  }
222 
228  template <typename ...option_types>
230  requires ((std::constructible_from<option_value_type, option_types> && ...))
232  value_list_validator(option_types && ...opts)
233  {
234  (values.emplace_back(std::forward<option_types>(opts)), ...);
235  }
237 
242  void operator()(option_value_type const & cmp) const
243  {
244  if (!(std::find(values.begin(), values.end(), cmp) != values.end()))
245  throw validation_error{detail::to_string("Value ", cmp, " is not one of ", std::views::all(values), ".")};
246  }
247 
253  template <std::ranges::forward_range range_type>
255  requires std::convertible_to<std::ranges::range_value_t<range_type>, option_value_type>
257  void operator()(range_type const & range) const
258  {
259  std::for_each(std::ranges::begin(range), std::ranges::end(range), [&] (auto cmp) { (*this)(cmp); });
260  }
261 
264  {
265  return detail::to_string("Value must be one of ", std::views::all(values), ".");
266  }
267 
268 private:
269 
272 };
273 
279 template <typename option_type, typename ...option_types>
281  requires (std::constructible_from<std::string, std::decay_t<option_types>> && ... &&
282  std::constructible_from<std::string, std::decay_t<option_type>>)
284 value_list_validator(option_type, option_types...) -> value_list_validator<std::string>;
285 
287 template <typename range_type>
289  requires (std::ranges::forward_range<std::decay_t<range_type>> &&
290  std::constructible_from<std::string, std::ranges::range_value_t<range_type>>)
292 value_list_validator(range_type && rng) -> value_list_validator<std::string>;
293 
295 template <typename option_type, typename ...option_types>
296 value_list_validator(option_type, option_types ...) -> value_list_validator<option_type>;
297 
299 template <typename range_type>
301  requires (std::ranges::forward_range<std::decay_t<range_type>>)
303 value_list_validator(range_type && rng) -> value_list_validator<std::ranges::range_value_t<range_type>>;
305 
319 {
320 public:
321 
324 
328  file_validator_base() = default;
333  virtual ~file_validator_base() = default;
335 
343  virtual void operator()(std::filesystem::path const & path) const = 0;
344 
352  template <std::ranges::forward_range range_type>
354  requires std::convertible_to<std::ranges::range_value_t<range_type>, std::filesystem::path const &>
356  void operator()(range_type const & v) const
357  {
358  std::for_each(v.begin(), v.end(), [&] (auto cmp) { this->operator()(cmp); });
359  }
360 
361 protected:
367  void validate_filename(std::filesystem::path const & path) const
368  {
369  // If no valid extensions are given we can safely return here.
370  if (extensions.empty())
371  return;
372 
373  // Check if extension is available.
374  if (!path.has_extension())
375  throw validation_error{detail::to_string("The given filename ", path.string(), " has no extension. Expected"
376  " one of the following valid extensions:", extensions, "!")};
377 
378  std::string file_path{path.filename().string()};
379 
380  // Leading dot indicates a hidden file is not part of the extension.
381  if (file_path.front() == '.')
382  file_path.erase(0, 1);
383 
384  // Store a string_view containing all extensions for a better error message.
385  std::string const all_extensions{file_path.substr(file_path.find(".") + 1)};
386 
387  // Compares the extensions in lower case.
388  auto case_insensitive_ends_with = [&] (std::string const & ext)
389  {
390  return case_insensitive_string_ends_with(file_path, ext);
391  };
392 
393  // Check if requested extension is present.
394  if (std::ranges::find_if(extensions, case_insensitive_ends_with) == extensions.end())
395  {
396  throw validation_error{detail::to_string("Expected one of the following valid extensions: ", extensions,
397  "! Got ", all_extensions, " instead!")};
398  }
399  }
400 
408  {
409  // Check if input directory is readable.
411  {
412  std::error_code ec{};
413  std::filesystem::directory_iterator{path, ec}; // if directory iterator cannot be created, ec will be set.
414  if (static_cast<bool>(ec))
415  throw validation_error{detail::to_string("Cannot read the directory ", path ,"!")};
416  }
417  else
418  {
419  // Must be a regular file.
421  throw validation_error{detail::to_string("Expected a regular file ", path, "!")};
422 
423  std::ifstream file{path};
424  if (!file.is_open() || !file.good())
425  throw validation_error{detail::to_string("Cannot read the file ", path, "!")};
426  }
427  }
428 
436  {
437  std::ofstream file{path};
438  detail::safe_filesystem_entry file_guard{path};
439 
440  bool is_open = file.is_open();
441  bool is_good = file.good();
442  file.close();
443 
444  if (!is_good || !is_open)
445  throw validation_error{detail::to_string("Cannot write ", path, "!")};
446 
447  file_guard.remove();
448  }
449 
452  {
453  if (extensions.empty())
454  return "";
455  else
456  return detail::to_string(" Valid file extensions are: [", extensions | views::join(std::string{", "}), "].");
457  }
458 
465  {
466  size_t const suffix_length{suffix.size()};
467  size_t const str_length{str.size()};
468  return suffix_length > str_length ?
469  false :
470  std::ranges::equal(str.substr(str_length - suffix_length), suffix, [] (char const chr1, char const chr2)
471  {
472  return std::tolower(chr1) == std::tolower(chr2);
473  });
474  }
475 
478 };
479 
502 template <typename file_t = void>
504 {
505 public:
506 
507  static_assert(std::same_as<file_t, void> || detail::has_type_valid_formats<file_t>,
508  "Expected either a template type with a static member called valid_formats (a file type) or void.");
509 
510  // Import from base class.
512 
526  {
527  if constexpr (!std::same_as<file_t, void>)
528  file_validator_base::extensions = detail::valid_file_extensions<typename file_t::valid_formats>();
529  }
530 
535  virtual ~input_file_validator() = default;
536 
547  requires std::same_as<file_t, void>
550  {
552  }
553 
554  // Import base class constructor.
557 
558  // Import the base::operator()
559  using file_validator_base::operator();
560 
566  virtual void operator()(std::filesystem::path const & file) const override
567  {
568  try
569  {
570  if (!std::filesystem::exists(file))
571  throw validation_error{detail::to_string("The file ", file, " does not exist!")};
572 
573  // Check if file is regular and can be opened for reading.
574  validate_readability(file);
575 
576  // Check extension.
577  validate_filename(file);
578  }
580  {
581  std::throw_with_nested(validation_error{"Unhandled filesystem error!"});
582  }
583  catch (...)
584  {
586  }
587  }
588 
591  {
592  return "The input file must exist and read permissions must be granted." +
594  }
595 };
596 
599 {
603  create_new
604 };
605 
632 template <typename file_t = void>
634 {
635 public:
636  static_assert(std::same_as<file_t, void> || detail::has_type_valid_formats<file_t>,
637  "Expected either a template type with a static member called valid_formats (a file type) or void.");
638 
639  // Import from base class.
641 
648  {}
649 
654  virtual ~output_file_validator() = default;
655 
664  : file_validator_base{}, mode{mode}
665  {
667  }
668 
669  // Import base constructor.
672 
682  {
683  if constexpr (!std::same_as<file_t, void>)
684  return detail::valid_file_extensions<typename file_t::valid_formats>();
685  return {};
686  }
687 
688  // Import the base::operator()
689  using file_validator_base::operator();
690 
696  virtual void operator()(std::filesystem::path const & file) const override
697  {
698  try
699  {
701  throw validation_error{detail::to_string("The file ", file, " already exists!")};
702 
703  // Check if file has any write permissions.
704  validate_writeability(file);
705 
706  validate_filename(file);
707  }
709  {
710  std::throw_with_nested(validation_error{"Unhandled filesystem error!"});
711  }
712  catch (...)
713  {
715  }
716  }
717 
720  {
722  return "Write permissions must be granted." + valid_extensions_help_page_message();
723  else // mode == create_new
724  return "The output file must not exist already and write permissions must be granted." +
726  }
727 
728 private:
731 };
732 
748 {
749 public:
750  // Import from base class.
752 
761  virtual ~input_directory_validator() = default;
762 
763  // Import base constructor.
766 
767  // Import the base::operator()
768  using file_validator_base::operator();
769 
775  virtual void operator()(std::filesystem::path const & dir) const override
776  {
777  try
778  {
779  if (!std::filesystem::exists(dir))
780  throw validation_error{detail::to_string("The directory ", dir, " does not exists!")};
781 
783  throw validation_error{detail::to_string("The path ", dir, " is not a directory!")};
784 
785  // Check if directory has any read permissions.
787  }
789  {
790  std::throw_with_nested(validation_error{"Unhandled filesystem error!"});
791  }
792  catch (...)
793  {
795  }
796  }
797 
800  {
801  return detail::to_string("An existing, readable path for the input directory.");
802  }
803 };
804 
820 {
821 public:
822  // Imported from base class.
824 
833  virtual ~output_directory_validator() = default;
834 
835  // Import base constructor.
838 
839  // Import the base::operator().
840  using file_validator_base::operator();
841 
847  virtual void operator()(std::filesystem::path const & dir) const override
848  {
849  bool dir_exists = std::filesystem::exists(dir);
850  // Make sure the created dir is deleted after we are done.
851  std::error_code ec;
852  std::filesystem::create_directory(dir, ec); // does nothing and is not treated as error if path already exists.
853  // if error code was set or if dummy.txt could not be created within the output dir, throw an error.
854  if (static_cast<bool>(ec))
855  throw validation_error{detail::to_string("Cannot create directory: ", dir, "!")};
856 
857  try
858  {
859  if (!dir_exists)
860  {
861  detail::safe_filesystem_entry dir_guard{dir};
862  validate_writeability(dir / "dummy.txt");
863  dir_guard.remove_all();
864  }
865  else
866  {
867  validate_writeability(dir / "dummy.txt");
868  }
869  }
871  {
872  std::throw_with_nested(validation_error{"Unhandled filesystem error!"});
873  }
874  catch (...)
875  {
877  }
878  }
879 
882  {
883  return detail::to_string("A valid path for the output directory.");
884  }
885 };
886 
905 {
906 public:
909 
913  regex_validator(std::string const & pattern_) :
914  pattern{pattern_}
915  {}
916 
921  void operator()(option_value_type const & cmp) const
922  {
923  std::regex rgx(pattern);
924  if (!std::regex_match(cmp, rgx))
925  throw validation_error{detail::to_string("Value ", cmp, " did not match the pattern ", pattern, ".")};
926  }
927 
934  template <std::ranges::forward_range range_type>
936  requires std::convertible_to<std::ranges::range_value_t<range_type>, option_value_type const &>
938  void operator()(range_type const & v) const
939  {
940  for (option_value_type const & file_name : v)
941  (*this)(file_name);
942  }
943 
946  {
947  return detail::to_string("Value must match the pattern '", pattern, "'.");
948  }
949 
950 private:
952  std::string pattern;
953 };
954 
955 namespace detail
956 {
957 
968 template <typename option_value_t>
969 struct default_validator
970 {
972  using option_value_type = option_value_t;
973 
975  void operator()(option_value_t const & /*cmp*/) const noexcept
976  {}
977 
980  {
981  return "";
982  }
983 };
984 
996 template <validator validator1_type, validator validator2_type>
998  requires std::common_with<typename validator1_type::option_value_type, typename validator2_type::option_value_type>
1000 class validator_chain_adaptor
1001 {
1002 public:
1004  using option_value_type = std::common_type_t<typename validator1_type::option_value_type,
1005  typename validator2_type::option_value_type>;
1006 
1010  validator_chain_adaptor() = delete;
1011  validator_chain_adaptor(validator_chain_adaptor const & pf) = default;
1012  validator_chain_adaptor & operator=(validator_chain_adaptor const & pf) = default;
1013  validator_chain_adaptor(validator_chain_adaptor &&) = default;
1014  validator_chain_adaptor & operator=(validator_chain_adaptor &&) = default;
1015 
1020  validator_chain_adaptor(validator1_type vali1_, validator2_type vali2_) :
1021  vali1{std::move(vali1_)}, vali2{std::move(vali2_)}
1022  {}
1023 
1025  ~validator_chain_adaptor() = default;
1027 
1036  template <typename cmp_type>
1038  requires std::invocable<validator1_type, cmp_type const> && std::invocable<validator2_type, cmp_type const>
1040  void operator()(cmp_type const & cmp) const
1041  {
1042  vali1(cmp);
1043  vali2(cmp);
1044  }
1045 
1048  {
1049  return detail::to_string(vali1.get_help_page_message(), " ", vali2.get_help_page_message());
1050  }
1051 
1052 private:
1054  validator1_type vali1;
1056  validator2_type vali2;
1057 };
1058 
1059 } // namespace detail
1060 
1088 template <validator validator1_type, validator validator2_type>
1090  requires std::common_with<typename std::remove_reference_t<validator1_type>::option_value_type,
1093 auto operator|(validator1_type && vali1, validator2_type && vali2)
1094 {
1095  return detail::validator_chain_adaptor{std::forward<validator1_type>(vali1),
1096  std::forward<validator2_type>(vali2)};
1097 }
1098 
1099 } // namespace seqan3
Adaptations of algorithms from the Ranges TS.
T begin(T... args)
A validator that checks whether a number is inside a given range.
Definition: validators.hpp:122
void operator()(option_value_type const &cmp) const
Tests whether cmp lies inside [min, max].
Definition: validators.hpp:139
option_value_t option_value_type
The type of value that this validator invoked upon.
Definition: validators.hpp:125
void operator()(range_type const &range) const
Tests whether every element in range lies inside [min, max].
Definition: validators.hpp:155
std::string get_help_page_message() const
Returns a message that can be appended to the (positional) options help page info.
Definition: validators.hpp:161
arithmetic_range_validator(option_value_type const min_, option_value_type const max_)
The constructor.
Definition: validators.hpp:131
An abstract base class for the file and directory validators.
Definition: validators.hpp:319
file_validator_base & operator=(file_validator_base &&)=default
Defaulted.
bool case_insensitive_string_ends_with(std::string_view str, std::string_view suffix) const
Helper function that checks if a string is a suffix of another string. Case insensitive.
Definition: validators.hpp:464
void validate_filename(std::filesystem::path const &path) const
Validates the given filename path based on the specified extensions.
Definition: validators.hpp:367
file_validator_base & operator=(file_validator_base const &)=default
Defaulted.
std::string valid_extensions_help_page_message() const
Returns the information of valid file extensions.
Definition: validators.hpp:451
virtual void operator()(std::filesystem::path const &path) const =0
Tests if the given path is a valid input, respectively output, file or directory.
std::string option_value_type
Type of values that are tested by validator.
Definition: validators.hpp:323
void operator()(range_type const &v) const
Tests whether every path in list v passes validation. See operator()(option_value_type const & value)...
Definition: validators.hpp:356
file_validator_base(file_validator_base &&)=default
Defaulted.
void validate_readability(std::filesystem::path const &path) const
Checks if the given path is readable.
Definition: validators.hpp:407
file_validator_base()=default
Defaulted.
file_validator_base(file_validator_base const &)=default
Defaulted.
std::vector< std::string > extensions
Stores the extensions.
Definition: validators.hpp:477
virtual ~file_validator_base()=default
void validate_writeability(std::filesystem::path const &path) const
Checks if the given path is writable.
Definition: validators.hpp:435
A validator that checks if a given path is a valid input directory.
Definition: validators.hpp:748
input_directory_validator(input_directory_validator &&)=default
Defaulted.
std::string get_help_page_message() const
Returns a message that can be appended to the (positional) options help page info.
Definition: validators.hpp:799
input_directory_validator & operator=(input_directory_validator &&)=default
Defaulted.
input_directory_validator()=default
Defaulted.
input_directory_validator & operator=(input_directory_validator const &)=default
Defaulted.
input_directory_validator(input_directory_validator const &)=default
Defaulted.
virtual void operator()(std::filesystem::path const &dir) const override
Tests whether path is an existing directory and is readable.
Definition: validators.hpp:775
virtual ~input_directory_validator()=default
Virtual Destructor.
A validator that checks if a given path is a valid input file.
Definition: validators.hpp:504
input_file_validator(input_file_validator const &)=default
Defaulted.
virtual ~input_file_validator()=default
Virtual destructor.
input_file_validator(std::vector< std::string > extensions)
Constructs from a given collection of valid extensions.
Definition: validators.hpp:545
std::string get_help_page_message() const
Returns a message that can be appended to the (positional) options help page info.
Definition: validators.hpp:590
input_file_validator(input_file_validator &&)=default
Defaulted.
input_file_validator & operator=(input_file_validator &&)=default
Defaulted.
virtual void operator()(std::filesystem::path const &file) const override
Tests whether path is an existing regular file and is readable.
Definition: validators.hpp:566
input_file_validator()
Default constructor.
Definition: validators.hpp:525
input_file_validator & operator=(input_file_validator const &)=default
Defaulted.
A validator that checks if a given path is a valid output directory.
Definition: validators.hpp:820
output_directory_validator()=default
Defaulted.
output_directory_validator & operator=(output_directory_validator const &)=default
Defaulted.
virtual ~output_directory_validator()=default
Virtual Destructor.
output_directory_validator(output_directory_validator &&)=default
Defaulted.
output_directory_validator(output_directory_validator const &)=default
Defaulted.
virtual void operator()(std::filesystem::path const &dir) const override
Tests whether path is writable.
Definition: validators.hpp:847
output_directory_validator & operator=(output_directory_validator &&)=default
Defaulted.
std::string get_help_page_message() const
Returns a message that can be appended to the (positional) options help page info.
Definition: validators.hpp:881
A validator that checks if a given path is a valid output file.
Definition: validators.hpp:634
output_file_validator(output_file_validator &&)=default
Defaulted.
output_file_validator(output_file_validator const &)=default
Defaulted.
output_file_validator & operator=(output_file_validator const &)=default
Defaulted.
virtual void operator()(std::filesystem::path const &file) const override
Tests whether path is does not already exists and is writable.
Definition: validators.hpp:696
static std::vector< std::string > default_extensions()
The default extensions of file_t.
Definition: validators.hpp:681
output_file_validator()
Default constructor.
Definition: validators.hpp:647
output_file_validator & operator=(output_file_validator &&)=default
Defaulted.
std::string get_help_page_message() const
Returns a message that can be appended to the (positional) options help page info.
Definition: validators.hpp:719
virtual ~output_file_validator()=default
Virtual Destructor.
output_file_validator(output_file_open_options const mode, std::vector< std::string > extensions=default_extensions())
Constructs from a given overwrite mode and a list of valid extensions.
Definition: validators.hpp:662
A validator that checks if a matches a regular expression pattern.
Definition: validators.hpp:905
std::string get_help_page_message() const
Returns a message that can be appended to the (positional) options help page info.
Definition: validators.hpp:945
void operator()(option_value_type const &cmp) const
Tests whether cmp lies inside values.
Definition: validators.hpp:921
void operator()(range_type const &v) const
Tests whether every filename in list v matches the pattern.
Definition: validators.hpp:938
std::string option_value_type
Type of values that are tested by validator.
Definition: validators.hpp:908
regex_validator(std::string const &pattern_)
Constructing from a vector.
Definition: validators.hpp:913
Argument parser exception thrown when an argument could not be casted to the according type.
Definition: exceptions.hpp:141
A validator that checks whether a value is inside a list of valid values.
Definition: validators.hpp:193
value_list_validator()=default
Defaulted.
void operator()(option_value_type const &cmp) const
Tests whether cmp lies inside values.
Definition: validators.hpp:242
value_list_validator(value_list_validator const &)=default
Defaulted.
option_value_t option_value_type
Type of values that are tested by validator.
Definition: validators.hpp:196
std::string get_help_page_message() const
Returns a message that can be appended to the (positional) options help page info.
Definition: validators.hpp:263
value_list_validator & operator=(value_list_validator &&)=default
Defaulted.
void operator()(range_type const &range) const
Tests whether every element in range lies inside values.
Definition: validators.hpp:257
value_list_validator(value_list_validator &&)=default
Defaulted.
~value_list_validator()=default
Defaulted.
value_list_validator & operator=(value_list_validator const &)=default
Defaulted.
value_list_validator(range_type rng)
Constructing from a range.
Definition: validators.hpp:217
T clear(T... args)
The Concepts library.
T create_directory(T... args)
T current_exception(T... args)
Auxiliary for pretty printing of exception messages.
Provides seqan3::debug_stream and related types.
T emplace_back(T... args)
T end(T... args)
Provides parser related exceptions.
T exists(T... args)
Provides concepts for core language types and relations that don't have concepts in C++20 (yet).
T filename(T... args)
This header includes C++17 filesystem support and imports it into namespace std::filesystem (independ...
T find(T... args)
T for_each(T... args)
auto operator|(validator1_type &&vali1, validator2_type &&vali2)
Enables the chaining of validators.
Definition: validators.hpp:1093
constexpr ptrdiff_t find_if
Get the index of the first type in a pack that satisfies the given predicate.
Definition: traits.hpp:209
auto const move
A view that turns lvalue-references into rvalue-references.
Definition: move.hpp:70
T has_extension(T... args)
A type that satisfies std::is_arithmetic_v<t>.
The concept for option validators passed to add_option/positional_option.
void operator()(option_value_type const &cmp) const
Validates the value 'cmp' and throws a seqan3::validation_error on failure.
std::string get_help_page_message() const
Returns a message that can be appended to the (positional) options help page info.
using option_value_type
The type of value on which the validator is called on.
Provides various utility functions.
T is_directory(T... args)
T is_regular_file(T... args)
Provides seqan3::views::join.
The main SeqAn3 namespace.
Definition: aligned_sequence_concept.hpp:29
output_file_open_options
Mode of an output file: Determines whether an existing file can be (silently) overwritten.
Definition: validators.hpp:599
@ create_new
Forbid overwriting the output file.
@ open_or_create
Allow to overwrite the output file.
SeqAn specific customisations in the standard namespace.
#define SEQAN3_RETURN_TYPE_CONSTRAINT(expression, concept_name,...)
Same as writing {expression} -> concept_name<type1[, ...]> in a concept definition.
Definition: platform.hpp:57
Adaptations of concepts from the standard library.
Adaptations of concepts from the Ranges TS.
T regex_match(T... args)
T rethrow_exception(T... args)
Provides seqan3::detail::safe_filesystem_entry.
T size(T... args)
T substr(T... args)
T throw_with_nested(T... args)
Provides traits for seqan3::type_list.
Provides various traits for template packs.
Provides various type traits on generic types.