添加生成help功能

This commit is contained in:
2024-02-05 01:33:44 +08:00
parent f994bae5cb
commit ded5c77a70
3 changed files with 39 additions and 0 deletions

View File

@@ -82,6 +82,9 @@ namespace ling {
const std::string &getError() const; const std::string &getError() const;
/// 生成help内容
std::string generateHelp(const std::string & title) const;
friend class Options; friend class Options;
}; };
} // ling } // ling

View File

@@ -4,6 +4,9 @@
#include "../include/Order.h" #include "../include/Order.h"
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept> #include <stdexcept>
#define THROW(errStr) do{ this->err = errStr; return false; } while(false) #define THROW(errStr) do{ this->err = errStr; return false; } while(false)
@@ -144,4 +147,25 @@ namespace ling {
const std::string &Order::getError() const { const std::string &Order::getError() const {
return err; return err;
} }
std::string Order::generateHelp(const std::string &title) const {
std::stringstream stream;
stream << title << std::endl;
std::cout << std::endl;
for (const auto &[fst, snd]: data) {
std::stringstream temp;
//即使参数有多个选项,也只输出前两个
if (snd.options.size() == 2) {
temp << std::left << std::setw(7) << (snd.options[0] + ",") << std::left << std::setw(18) << snd.options[1];
} else {
if (snd.options[0].at(0) == '-' && snd.options[0].at(1) == '-')
temp << std::left << std::setw(7) << "" << std::left << std::setw(18) << snd.options[0];
else
temp << std::left << std::setw(25) << snd.options[0];
}
temp << std::left << std::setw(55) << snd.memage;
stream << temp.str() << std::endl;
}
return stream.str();
}
} // ling } // ling

View File

@@ -97,3 +97,15 @@ TEST(Option, 匿名参数测试3) {
if (order.analysis()) if (order.analysis())
ASSERT_FALSE("匿名参数数量超出限制,但是没有抛出异常!"); ASSERT_FALSE("匿名参数数量超出限制,但是没有抛出异常!");
} }
TEST(Option, Help生成) {
ling::Order order({"-pts", "hello world!", "hello!", "--all", "--ok", "world"});
order.addAnonymity(1);
const auto pts = order.addOption({"-pts", "--pts"}, ling::Order::Type::STRING, "测试参数");
const auto all = order.addOption({"-all", "--all"},"测试参数");
const auto ok = order.addOption({"-ok", "--ok"},"测试参数");
const auto cancel = order.addOption({"--cancel"},"测试参数");
auto help = order.generateHelp("test [选项] .. [参数]\n测试命令");
std::cout << help << std::endl;
}