Commit 464a8eb65d0a529390e7f8483dea2cb39107618f

Authored by Jarryd Beck
1 parent f3582c48

Add required options helper

Fixes #44. Adds a helper function for checking required options.
include/cxxopts.hpp
... ... @@ -397,6 +397,18 @@ namespace cxxopts
397 397 }
398 398 };
399 399  
  400 + class option_required_exception : public OptionParseException
  401 + {
  402 + public:
  403 + option_required_exception(const std::string& option)
  404 + : OptionParseException
  405 + (
  406 + u8"Option ‘" + option + u8"’ is required but not present"
  407 + )
  408 + {
  409 + }
  410 + };
  411 +
400 412 namespace values
401 413 {
402 414 template <typename T>
... ... @@ -841,9 +853,25 @@ namespace cxxopts
841 853 std::string m_group;
842 854 };
843 855  
844   - namespace
  856 + // A helper function for setting required arguments
  857 + void
  858 + check_required
  859 + (
  860 + const Options& options,
  861 + const std::vector<std::string>& required
  862 + )
845 863 {
  864 + for (auto& r : required)
  865 + {
  866 + if (options.count(r) == 0)
  867 + {
  868 + throw option_required_exception(r);
  869 + }
  870 + }
  871 + }
846 872  
  873 + namespace
  874 + {
847 875 constexpr int OPTION_LONGEST = 30;
848 876 constexpr int OPTION_DESC_GAP = 2;
849 877  
... ...
test/options.cpp
... ... @@ -100,6 +100,27 @@ TEST_CASE(&quot;Short options&quot;, &quot;[options]&quot;)
100 100 cxxopts::invalid_option_format_error);
101 101 }
102 102  
  103 +TEST_CASE("Required arguments", "[options]")
  104 +{
  105 + cxxopts::Options options("required", " - test required options");
  106 + options.add_options()
  107 + ("one", "one option")
  108 + ("two", "second option")
  109 + ;
  110 +
  111 + Argv argv({
  112 + "required",
  113 + "--one"
  114 + });
  115 +
  116 + auto aargv = argv.argv();
  117 + auto argc = argv.argc();
  118 +
  119 + options.parse(argc, aargv);
  120 + REQUIRE_THROWS_AS(cxxopts::check_required(options, {"two"}),
  121 + cxxopts::option_required_exception);
  122 +}
  123 +
103 124 TEST_CASE("No positional", "[positional]")
104 125 {
105 126 cxxopts::Options options("test_no_positional",
... ...