13 #ifndef __STOUT_SUBCOMMAND_HPP__ 14 #define __STOUT_SUBCOMMAND_HPP__ 59 #define INSERT(z, N, _) subcommands.push_back( c ## N ); 60 #define TEMPLATE(Z, N, DATA) \ 61 static int dispatch( \ 62 const Option<std::string>& prefix, \ 65 ENUM_PARAMS(N, Subcommand* c)) \ 67 std::vector<Subcommand*> subcommands; \ 68 REPEAT_FROM_TO(0, N, INSERT, _) \ 69 return dispatch(prefix, argc, argv, subcommands); \ 76 explicit Subcommand(
const std::string& _name) : name_(_name) {}
79 std::string
name()
const {
return name_; }
95 static std::string usage(
96 const std::string& argv0,
97 const std::vector<Subcommand*>& subcommands);
103 const std::vector<Subcommand*>& subcommands);
113 inline std::string Subcommand::usage(
114 const std::string& argv0,
115 const std::vector<Subcommand*>& subcommands)
117 std::ostringstream stream;
119 stream <<
"Usage: " << argv0 <<
" <subcommand> [OPTIONS]\n\n" 120 <<
"Available subcommands:\n" 124 foreach (
Subcommand* subcommand, subcommands) {
125 stream <<
" " << subcommand->
name() <<
"\n";
132 inline int Subcommand::dispatch(
136 const std::vector<Subcommand*>& subcommands)
138 if (subcommands.empty()) {
139 std::cerr <<
"No subcommand is found" << std::endl;
145 foreach (
Subcommand* subcommand, subcommands) {
147 std::cerr <<
"Multiple subcommands have name '" 148 << subcommand->
name() <<
"'" << std::endl;
151 names.insert(subcommand->
name());
155 std::cerr << usage(argv[0], subcommands) << std::endl;
159 if (std::string(argv[1]) ==
"help") {
161 std::cout << usage(argv[0], subcommands) << std::endl;
167 argv[2] = (
char*)
"--help";
170 foreach (
Subcommand* subcommand, subcommands) {
171 if (subcommand->
name() == argv[1]) {
176 std::cerr <<
"Failed to parse the flags: " << load.
error() << std::endl;
184 std::cerr <<
"Subcommand '" << argv[1] <<
"' is not available\n" 185 << usage(argv[0], subcommands) << std::endl;
189 #endif // __STOUT_SUBCOMMAND_HPP__ std::string name() const
Definition: subcommand.hpp:79
constexpr const char * prefix
Definition: os.hpp:96
bool contains(const Elem &elem) const
Definition: hashset.hpp:102
REPEAT_FROM_TO(1, 11, TEMPLATE, _) explicit Subcommand(const std
Definition: subcommand.hpp:72
virtual flags::FlagsBase * getFlags()
Definition: subcommand.hpp:91
Definition: subcommand.hpp:41
#define TEMPLATE(Z, N, DATA)
Definition: subcommand.hpp:60
virtual Try< Warnings > load(const std::string &prefix)
Definition: flags.hpp:565
static Try error(const E &e)
Definition: try.hpp:43
bool isError() const
Definition: try.hpp:78
virtual ~Subcommand()
Definition: subcommand.hpp:77