Skip to content

Commit 36fd3fd

Browse files
[Util] Extend ArgParser to support lists.
Extend the `ArgParser` to support CLI arguments with lists of strings. For example, one can now implement an argument like ``` --colors "yellow,green,navy blue,pink" ``` The type of the argument must be `std::vector<std::string_view>`. To implement such a CLI argument in our shell, you can do ```cpp ADD(std::vector<std::string_view>, void *_, nullptr, nullptr, "--colors", "A comma-separated list of colors.", [&](std::vector<std::string_view> colors) { std::cerr << "received colors are:\n"; for (auto color : colors) std::cerr << " " << color << '\n'; }); ```
1 parent 81e6e22 commit 36fd3fd

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/util/ArgParser.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <iomanip>
66
#include <limits>
77
#include <string>
8+
#include <string_view>
89
#include <type_traits>
910

1011

@@ -78,6 +79,35 @@ void ArgParser::OptionImpl<const char*>::parse(const char **&argv) const
7879
callback(*argv);
7980
}
8081

82+
/*----- List of String -----------------------------------------------------------------------------------------------*/
83+
template<>
84+
void ArgParser::OptionImpl<std::vector<std::string_view>>::parse(const char **&argv) const
85+
{
86+
if (not *++argv) {
87+
std::cerr << "missing argument" << std::endl;
88+
std::exit(EXIT_FAILURE);
89+
}
90+
91+
std::vector<std::string_view> args;
92+
std::string_view sv(*argv);
93+
94+
if (sv.empty()) {
95+
callback(std::move(args));
96+
return;
97+
}
98+
99+
std::string_view::size_type begin = 0;
100+
for (;;) {
101+
auto end = sv.find(',', begin);
102+
args.emplace_back(sv.substr(begin, end - begin));
103+
if (end == std::string_view::npos)
104+
break;
105+
begin = end + 1; // skip comma ','
106+
}
107+
108+
callback(std::move(args));
109+
}
110+
81111
//----------------------------------------------------------------------------------------------------------------------
82112

83113
void ArgParser::print_args(std::ostream &out) const

0 commit comments

Comments
 (0)