1 概述
CLI11提供了您在强大的命令行解析器中所期望的所有功能,具有美观、简洁的语法,并且以单个文件的形式提供,便于包含在项目中。这很容易适用于小型项目,但功能强大,足以支持复杂的命令行项目,并且可以针对框架进行定制。
本来准备使用Boost库中program_options,不过boost整个头文件就有170MB,对于小项目来说使用成本很高,还得编译boost库,感觉不划算。
CLI11功能强大可以直接包含头文件使用,对小项目很友好。本文后面讲述CLL11的使用实例。
2 实例
2.1 参数设计
一个命令行ssh终端程序,其功能如下:
- 登录ssh服务器,执行命令后退出。
- 登录ssh服务器,运行交互shell。
- 登录ssh服务器,执行上传文件/目录后退出。
- 登录ssh服务器,执行下载文件/目录后退出。
- 上传下载文件可以通过SCP或SFTP协议。
命令参数设计如下:
A ssh term of cmdline
Usage: FlySSH [OPTIONS] [src] [dst]
Options:
--help Print this help message and exit
-u,--user User for login server
-P,--password Password for login server
-h,--host Host of ssh server
-p,--port Port of ssh server
-e,--exec Exec commands
-i,--interactive Run ssh shell
-s,--subsystem ENUM:value in {
scp->0,sftp->1} OR {
0,1}
Subsystem: scp or sftp
-d,--direction ENUM:value in {
download->1,upload->0} OR {
1,0}
Operation direction: upload or download
-t,--target ENUM:value in {
dir->1,file->0} OR {
1,0}
Target type: file or dir
2.2 实现
定义一类型AppArgs来管理命令行参数。
2.2.1 头文件
#ifndef APPARGS_H
#define APPARGS_H
#include <CLI/CLI11.hpp>
#include <string>
enum class SubSystem : int {
Scp, Sftp };
enum class Direction : int {
Upload, Download };
enum class Target : int {
File, Dir };
class AppArgs
{
CLI::App app_;
std::string user_;
std::string password_;
std::string host_;
uint16_t port_ = 22;
bool isInteractive_ = false;
SubSystem subSystem_ = SubSystem::Sftp;
Direction direction_ = Direction::Upload;
Target target_ = Target::File;
std::string srcPath_;
std::string dstPath_;
public:
AppArgs();
bool parse(int argc, char *argv[]);
void usage();
std::string user() const {
return user_; }
std::string password() const {
return password_; }
std::string host() const {
return host_; }
uint16_t port() const {
return port_; }
bool hasCommand() const;
std::string command() const;
bool isInteractive<