parse.hh (2300B)
1 #ifndef __GUCK__PARSE__GUARD__ 2 #define __GUCK__PARSE__GUARD__ 3 4 #include <string> 5 #include <vector> 6 #include <unordered_map> 7 #include <algorithm> 8 #include <iostream> 9 10 enum option_type_t { longopt, shortopt }; 11 12 struct option_t 13 { 14 option_t() = default; 15 16 option_t(option_type_t _type) 17 : type(_type), 18 has_value(false), 19 set(false) 20 {} 21 22 option_t(option_type_t _type, std::string _flag, 23 std::string _desc, bool _has_value = false) 24 : flag(_flag), 25 desc(_desc), 26 has_value(_has_value), 27 set(false) 28 {} 29 30 option_type_t type = shortopt; 31 std::string flag; 32 std::string desc; 33 std::string value; 34 bool has_value, set; 35 }; 36 37 38 class parser_t 39 { 40 public: 41 parser_t(int argc, char** argv) 42 : m_opts(argv, argv + argc), 43 m_optlist({ 44 // short options flag description 45 { option_type_t::shortopt, "h", "print help message" }, 46 { option_type_t::shortopt, "v", "print version information and quit" }, 47 48 // long options flag description has value 49 { option_type_t::longopt, "help", "print help message", false }, 50 { option_type_t::longopt, "version", "print version information and quit", false }, 51 { option_type_t::longopt, "no-config", "do not load configuration file", false }, 52 { option_type_t::longopt, "config-path", "path to configuration file", true }, 53 }) 54 { 55 for (auto& opt : m_optlist) 56 m_optmap[opt.flag] = opt; 57 58 std::vector<std::string>::iterator it; 59 if ((it = std::find(m_opts.begin(), m_opts.end(), "--")) != m_opts.end()) { 60 std::move(it + 1, m_opts.end(), std::back_inserter(m_args)); 61 m_opts.erase(it, m_opts.end()); 62 } 63 } 64 65 void parse(); 66 void setopt(std::string, std::string = ""); 67 68 std::pair<int, std::vector<char*>> getargs(); 69 70 private: 71 std::vector<std::string> m_opts; 72 std::vector<std::string> m_args; 73 74 std::vector<option_t> m_optlist; 75 std::unordered_map<std::string, option_t> m_optmap; 76 77 }; 78 79 #endif//__GUCK__PARSE__GUARD__