命令行解析工具源码样例(未经编译,不少地方数据转换未展示,仅供参考)
CmdLineParser.h/cpp
#ifndef EXAMPLE_CMDLINEPARSER_H
#define EXAMPLE_CMDLINEPARSER_H
#include <string>
#include <iostream>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
class CmdLineParser final {
public:
CmdLineParser();
~CmdLineParser() = default;
CmdLineParser(const CmdLineParser&) = delete;
CmdLineParser operator=(const CmdLineParser&) = delete;
int parseArgs(const int argc, char **argv);
const std::string& getFileContent()
{
return file_content_;
}
const std::string& getModuleName()
{
return module_name_;
}
const std::string& getFileName()
{
return file_name_;
}
private:
void SetCommonOptions();
void SetOptions();
void SetCommandLineOptions();
void check();
bool isValidOperation();
private:
po::options_description command_line_options_;
po::options_description common_options_;
po::variables_map vm_;
std::string cmd_;
std::string operation_;
std::string file_name_;
std::string module_name_;
std::string filter_path_;
};
#endif //EXAMPLE_CMDLINEPARSER_H
#include <fstream> // std::ifstream
#include "CmdLineParser.h"
CmdLineParser::CmdLineParser() {
SetOptions();
}
void CmdLineParser::SetOptions() {
SetCommandLineOptions();
SetCommonOptions();
}
void CmdLineParser::SetCommandLineOptions() {
command_line_options_.add_options()
("help,h", "display this help message")
("command,c", po::value<std::string>(&cmd_),
"the command list is: add, delete, modify")
;
}
void CmdLineParser::SetCommonOptions() {
common_options_.add_options()
("file,f", po::value<std::string>(&file_name_),
"configure file or event file directory.")
("default-operation,d", po::value<std::string>(&operation_)->default_value("add"),
"It could be \"do_1\",\"do_2\", \"do_3\". Default value is \"do_1\" ")
("filter-xpath,x", po::value<std::string>(&filter_xpath_),
"indicate that the select attribute of the <filter> element contains an XPath expression.")
("module,m", po::value<std::string>(&module_name_),"module name.")
("example",
"your_cli -c add --default-operation do_1 -f config.xml")
;
}
int CmdLineParser::parseArgs(const int argc, char **argv) {
po::options_description cmd_opts;
cmd_opts.add(command_line_options_).add(common_options_);
store(po::command_line_parser(argc, argv).
options(cmd_opts).run(), vm_);
notify(vm_);
check();
return isValid()? TOOL_OK : TOOL_ERR;
}
bool CmdLineParser::isValidOperation()
{
if((operation_ == "add") || (operation_ == "delete") || (operation_ == "modify"))
{
return true;
}
return false;
}
std::string CmdLineParser::readFile(const std::string &filepath)
{
std::ifstream ifStr(filepath);
if(!ifStr.is_open())
{
throw std::runtime_error(std::string("Open file failed: ") + filepath + " " + strerror(errno));
}
std::ostringstream sin;
sin << ifStr.rdbuf();
ifStr.close();
return sin.str();
}
const std::string HELP_OPTION = "help";
const std::string COMMAND_OPTION = "command";
void CmdLineParser::check() {
if(vm_.count(HELP_OPTION))
{
std::cout << command_line_options_ << std::endl;
std::cout << common_options_ << std::endl;
}
else if (vm_.count(COMMAND_OPTION))
{
if (((cmd_ == "add") || (cmd_ == "delete")|| (cmd_ == "modify")) && vm_.count(FILE_OPTION) && isValidOperation())
file_content_ = readFile(file_name_);
}
}
cliend.h
#define TOOL_CLIENTMANAGER_H
#include "CmdLineParser.h"
#include "UdsZmqHandler.h"
class Client final {
public:
Client() ;
~Client() = default;
int parseandrun(const int argc, char **argv);
private:
int parse(const int argc, char **argv);
int sendCommand2Server();
int recvResponse();
UdsZmqHandler udsZmqHandler_;
CmdLineParser cmdLineParser_;
};
#endif //TOOL_CLIENTMANAGER_H
client.cpp
#include "Client.h"
#include <boost/lexical_cast.hpp>
Client::Client():udsZmqHandler_(zmq::socket_type::req)
{
}
int Client::parseandrun(const int argc, char **argv) {
try
{
int ret = parse(argc, argv);
if(TOOL_OK != ret)
{
return ret;
}
ret = sendCommand2Server();
if(TOOL_OK != ret)
{
return ret;
}
return recvResponse();
}
catch (zmq::error_t& e)
{
std::cout <<"client: ZMQ send/recv with errno: " << e.what() <<std::endl;
}
catch (const boost::bad_lexical_cast &e)
{
std::cout <<"client: cmd parse with errno: " << e.what() <<std::endl;
}
return TOOL_ERR;
}
int Client::parse(const int argc, char **argv) {
try {
return cmdLineParser_.parseArgs(argc, argv);
}
catch (const std::exception& e) {
std::cout<< e.what() << std::endl;
return TOOL_ERR;
}
}
int Client::sendCommand2Server() {
Message msg;
msg.createReqMessage(cmdLineArgParser_.getCmd(),
cmdLineArgParser_.getOperation(),
cmdLineArgParser_.getFileContent(),
cmdLineArgParser_.getModule(),
cmdLineArgParser_.getFileName());
return udsZmqHandler_.send(msg);
}
int Client::recvResponse() {
Message msg;
udsZmqHandler_.recv(msg);
auto &protobufmsg = msg.getProtoMsg();
if(protobufmsg.response().status() == tplcli::Response_Status_SUCCESS)
{
std::cout << "---recv from server, command success" << std::endl;
return TOOL_OK;
}
else
{
std::cout << "---recv from server, command failed" << std::endl;
std::cout << "---error Info:" << protobufmsg.response().errorinfo() << std::endl;
std::cout << "---xml data:" << protobufmsg.response().xmldata() << std::endl;
return TOOL_ERR;
}
}
main.cpp
#include "Client.h"
int main(int argc, char** argv) {
Client client;
return client.runandparse(argc, argv);
}