From 29199b2e29ac70f8df1900539317e591eee633c7 Mon Sep 17 00:00:00 2001 From: sunrisepeak Date: Thu, 3 Dec 2026 06:29:27 +0900 Subject: [PATCH] 0.0.7: subcommands in groups and in one order for help, snapshot and messages; a help epilogue - `App::group(s)` on a subcommand: the heading its parent's help lists it under. A group takes the place of the first command that declares it; the commands without one follow the groups. - `App::help_options({ .order = alphabetical, .ungrouped = "..." })`: by name inside a group and among the rest, and a heading for the rest. Declared order stays the default. - `App::help_epilogue(s)`: printed after the subcommands (the lines to copy, where to read on). - `CompletionOptions::group`: the completion command's heading, without giving that group its place. - One listing serves `print_help`, `snapshot(app)` and the 'a subcommand is required' message. A hidden command is no longer named by that message, and the snapshot now leads with the completion command where 0.0.6 appended it. - Nothing opted in: the help is byte-identical to 0.0.6, and no parse changes: the first declared subcommand still wins a name. - Tests: eight cases in `tests/cmdline_test.cpp` (the default output, groups and by name, declared inside a group, the snapshot's order, the completion command leading, the epilogue, the message, the parse untouched); 59 + 12 pass on mcpp 2026.11.8.1. - `docs/api.md` states the rules of the listing with an example; README names the feature; version 0.0.7. --- README.md | 1 + docs/api.md | 37 +++++++++++- mcpp.toml | 2 +- src/cmdline.cppm | 129 +++++++++++++++++++++++++++++++++++------ tests/cmdline_test.cpp | 114 ++++++++++++++++++++++++++++++++++++ 5 files changed, 261 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index bad2b52..2ba6165 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ - **Shell 补全** — `app.completion()` 一次调用开启;程序以自己的命令树回答(`__complete`),bash、zsh、fish、PowerShell 的适配脚本只有几行,不含命令树 - **数值选项** — `value_type()` 声明选项取 `T` 类型的数字,解析时用 `std::from_chars` 校验,不合法就是解析错误;`value_as(name)` 读回 +- **分组的 help** — 子命令的 `.group(s)` 给出标题,`.help_options({ .order = alphabetical, .ungrouped = "…" })` 定次序,`.help_epilogue(s)` 在列表后写例子;help、补全候选与“缺子命令”的报错用同一份列表 ## 快速开始 diff --git a/docs/api.md b/docs/api.md index a7e0724..ac64a83 100644 --- a/docs/api.md +++ b/docs/api.md @@ -13,6 +13,8 @@ | `Argv` | `std::vector` 的别名,用于 `parse_from` | | `Shell` | 目标 shell 枚举:`bash` / `fish` / `zsh` / `powershell` | | `Command` | 命令树快照,补全引擎读取它 | +| `CompletionOptions` | 补全的开启方式:可见命令名、隐藏入口、它在 help 里的分组 | +| `HelpOrder` · `HelpOptions` | help 列出子命令的次序与标题(`App::help_options`,见“帮助的列表”) | 解析返回 `ParseResult`,即 `std::expected`。`-h`/`--help`、`--version` 时,`ParseError::kind` 分别为 `help` / `version`(补全见“Shell 补全”,为 `completion`),不携带 `message`,通过 `is_error()` 可区分真实错误。 @@ -30,7 +32,36 @@ | `.parse(argc, argv)` `.parse_from(Argv)` `.parse_from(string_view)` | 解析,返回 `ParseResult` | | `.run(parsed)` | 执行解析结果所命中的命令的 action,返回其退出码(规则见“分发规则”) | | `.run(argc, argv)` `.run(Argv)` | parse + dispatch,返回退出码(推荐主入口):help/version 为 0,解析错误写入标准错误并返回 2 | -| `.print_help(program_name)` | 打印帮助 | +| `.print_help(program_name)` | 打印帮助(子命令的列表见“帮助的列表”) | +| `.group(s)` | 子命令:父命令的 help 把它列在哪个标题下;不给,就排在各分组之后 | +| `.help_options(HelpOptions)` | help 如何列出子命令:组内按声明或按名字,未分组命令的标题 | +| `.help_epilogue(s)` | 子命令列表之后原样打印的一段:可照抄的例子、下一步读什么 | + +### 帮助的列表(自 0.0.7) + +`help`、`snapshot(app)` 与“缺子命令”的报错按同一份列表排列子命令,三者一致;解析不受影响,先声明的子命令仍然先匹配。 + +- 子命令的 `.group(s)` 是它的标题。分组按第一个声明它的命令出现;没有分组的命令排在其后,`HelpOptions::ungrouped` + 非空时给出它们的标题。 +- 组内与未分组之内按声明次序(`HelpOrder::declared`,缺省)或按名字(`HelpOrder::alphabetical`)。 +- 补全命令(`CompletionOptions::command`)当作先于其它命令声明的一个:缺省时排第一,与 0.0.6 的 help 相同; + `CompletionOptions::group` 给它标题,但不决定那个分组的位置。 +- 什么都没选时,help 与 0.0.6 逐字节相同;变化只有一处:`snapshot` 的子命令以补全命令开头(0.0.6 把它放在末尾)。 + 隐藏的命令不在列表里,也不再被“缺子命令”的报错点名。 + +```cpp +(void)app.completion({.command = "completion", .entry = "__complete", .group = "OTHER"}) + .help_options({.order = cmdline::HelpOrder::alphabetical, .ungrouped = "MORE"}) + .help_epilogue("EXAMPLES:\n $ myapp auth add me\n") + .subcommand(cmdline::App("auth").group("START").description("accounts")) + .subcommand(cmdline::App("config").group("START").description("settings")); +// SUBCOMMANDS: +// START: +// auth accounts +// config settings +// OTHER: +// completion The completion script for a shell: bash, zsh, fish, powershell +``` --- @@ -40,7 +71,7 @@ **Option**:`.short_name(c)` `.long_opt(s)` `.help(s)` `.takes_value(bool)` `.value_name(s)` `.multiple(bool)` `.global(bool)` `.values({...})` `.value_hint(h)` `.complete(fn)` -**App**(子命令):`.hidden(bool)`;根命令:`.completion(options)`(见“Shell 补全”) +**App**(子命令):`.hidden(bool)` `.group(s)`;根命令:`.completion(options)`(见“Shell 补全”) `.help_options(HelpOptions)` `.help_epilogue(s)` --- @@ -243,7 +274,7 @@ app.subcommand(cmdline::App("add").description("Add").arg(cmdline::Arg("x").requ | `completions::render(answer)` | `Answer` → 上述文本协议 | | `completions::adapter(shell, program, entry)` | 某个 shell 的适配脚本 | | `completions::classify(word, isSubcommand)` | 一个词对一个命令的含义:`--`、长选项(含 `--k=v`)、短选项、子命令、位置参数;解析与补全共用 | -| `snapshot(app)` | 命令树快照(自 0.0.5):每个命令含自己的 `-h`/`--help`,有版本的命令含 `--version`;隐藏命令不在其中 | +| `snapshot(app)` | 命令树快照(自 0.0.5):每个命令含自己的 `-h`/`--help`,有版本的命令含 `--version`;隐藏命令不在其中;子命令的次序与 help 相同(自 0.0.7) | `generate_completions(cmd|app, shell[, out])` 与 `App::completions(shell)` 的签名不变,自 0.0.6 起输出适配脚本,而不是 写出整棵命令树的脚本。 diff --git a/mcpp.toml b/mcpp.toml index 75bad53..fafa847 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,7 +1,7 @@ [package] namespace = "mcpplibs" name = "cmdline" -version = "0.0.6" +version = "0.0.7" description = "A simple command-line parsing library/framework for modern C++" license = "Apache-2.0" authors = ["mcpplibs"] diff --git a/src/cmdline.cppm b/src/cmdline.cppm index 532c626..9bcf243 100644 --- a/src/cmdline.cppm +++ b/src/cmdline.cppm @@ -17,7 +17,8 @@ class ArgBuilder; export class App; /// The command tree as declared, with the options the parse adds itself (`-h/--help`, and /// `--version` when a version is set): what a completion script, a manual page or a tool's -/// listing of its own commands and options is generated from. +/// listing of its own commands and options is generated from; its subcommands are in the +/// order the command's help lists them (since 0.0.7, `HelpOptions`). export [[nodiscard]] completions::Command snapshot(const App& app); export using Argv = std::vector; @@ -25,10 +26,28 @@ export using Argv = std::vector; /// How `App::completion` offers completions: `entry` is the hidden command a /// shell's adapter calls with the words to complete; `command`, when not /// empty, a command that prints the adapter for a shell (`myapp completions -/// bash`), listed with the others. +/// bash`), listed with the others: as a command declared before them, among +/// the commands without a group — or under `group`, when one is named. export struct CompletionOptions { std::string command = "completions"; std::string entry = "__complete"; + std::string group; +}; + +/// The order a help lists a command's subcommands in (`App::help_options`): +/// as declared, or by name inside a group and among the commands without one. +export enum class HelpOrder { declared, alphabetical }; + +/// How a command's help lists its subcommands. A subcommand's `group` is the +/// heading it is listed under; the groups come in the order of the first +/// command that names each, the commands without a group after them, under +/// `ungrouped` when it is not empty. The same order is what `snapshot` hands +/// out and what a run names when a subcommand is required, so a tool's help, +/// its completions and its messages agree. None of it touches a parse: the +/// first declared subcommand still wins a name. +export struct HelpOptions { + HelpOrder order = HelpOrder::declared; + std::string ungrouped; }; export using detail::Arg; export using detail::Option; @@ -49,7 +68,8 @@ public: App& operator=(App&&) noexcept = default; App(const App& other) : name_(other.name_), version_(other.version_), description_(other.description_), author_(other.author_), args_(other.args_), options_(other.options_), subcommands_(other.subcommands_), action_(other.action_), - hidden_(other.hidden_), completion_(other.completion_) {} + hidden_(other.hidden_), completion_(other.completion_), group_(other.group_), help_options_(other.help_options_), + epilogue_(other.epilogue_) {} App& operator=(const App& other) { if (this == &other) return *this; name_ = other.name_; @@ -62,6 +82,9 @@ public: action_ = other.action_; hidden_ = other.hidden_; completion_ = other.completion_; + group_ = other.group_; + help_options_ = other.help_options_; + epilogue_ = other.epilogue_; return *this; } @@ -84,6 +107,24 @@ public: return *this; } + /// The heading the parent's help lists this command under; none, and it + /// follows the groups. + [[nodiscard]] App& group(std::string_view name) { + group_ = name; + return *this; + } + /// How this command's help lists its subcommands. + [[nodiscard]] App& help_options(HelpOptions options) { + help_options_ = std::move(options); + return *this; + } + /// Printed after the subcommands of this command's help: the lines to + /// copy, where to read on. A missing final newline is added. + [[nodiscard]] App& help_epilogue(std::string_view text) { + epilogue_ = text; + return *this; + } + [[nodiscard]] App& version(std::string_view version) { version_ = version; return *this; @@ -170,7 +211,7 @@ public: std::string command(name_); for (std::size_t i = 1; i < path.size(); ++i) command += " " + path[i].first->name_; std::string names; - for (const auto& sub : named.subcommands_) names += (names.empty() ? "" : ", ") + sub.name_; + for (const auto& c : listed(named, true)) names += (names.empty() ? "" : ", ") + std::string(c.name); std::println(std::cerr, "{}: a subcommand is required: {}", command, names); std::println(std::cerr, "{}: see '{} --help'", name_, command); return 2; @@ -206,20 +247,22 @@ public: } const bool listsCompletion = completion_ && !completion_->command.empty() && (program_name.empty() || program_name == name_); - if (std::ranges::any_of(subcommands_, [](const App& s) { return !s.hidden_; }) || listsCompletion) { + const auto commands = listed(*this, listsCompletion); + if (!commands.empty()) { std::println("\nSUBCOMMANDS:"); - if (listsCompletion) { - std::string padded(completion_->command); - while (padded.size() < 12) padded += ' '; - std::println(" {} The completion script for a shell: bash, zsh, fish, powershell", padded); - } - for (const auto& sub : subcommands_) { - if (sub.hidden_) continue; - std::string padded(sub.name_); + std::string_view heading; // the heading the last line was listed under + for (const auto& c : commands) { + const std::string_view under = c.group.empty() ? std::string_view(help_options_.ungrouped) : c.group; + if (under != heading) { + if (!under.empty()) std::println(" {}:", under); + heading = under; + } + std::string padded(c.name); while (padded.size() < 12) padded += ' '; - std::println(" {} {}", padded, sub.description_.empty() ? "" : sub.description_); + std::println(" {} {}", padded, c.description); } } + if (!epilogue_.empty()) std::print("\n{}{}", epilogue_, epilogue_.ends_with('\n') ? "" : "\n"); } [[nodiscard]] std::string completions(Shell shell) const; @@ -264,6 +307,49 @@ private: return run(*result); } + // A line of a subcommand list: a declared command, or the one that prints + // a completion adapter (no App behind it). + struct Listed { + const App* sub = nullptr; + std::string_view name; + std::string_view description; + std::string_view group; + }; + + // The subcommands a help lists, in its order: a group where the first + // declared command that names it was declared, the commands without one + // after the groups, declared (a stable sort keeps it) or by name inside + // either. The completion command is listed as one declared before the + // others, under its group when it names one, without giving that group + // its place. A hidden command is not listed. + [[nodiscard]] static std::vector listed(const App& app, bool with_completion) { + std::vector out; + if (with_completion && app.completion_ && !app.completion_->command.empty()) + out.push_back({nullptr, app.completion_->command, + "The completion script for a shell: bash, zsh, fish, powershell", app.completion_->group}); + for (const auto& sub : app.subcommands_) { + if (sub.hidden_) continue; + out.push_back({&sub, sub.name_, sub.description_, sub.group_}); + } + std::vector groups; + // A group's place is where the first declared command names it. + for (const auto& c : out) + if (c.sub && !c.group.empty() && std::ranges::find(groups, c.group) == groups.end()) groups.push_back(c.group); + for (const auto& c : out) + if (!c.sub && !c.group.empty() && std::ranges::find(groups, c.group) == groups.end()) groups.push_back(c.group); + const auto rank = [&groups](std::string_view g) { + const auto it = std::ranges::find(groups, g); + return it == groups.end() ? groups.size() : static_cast(it - groups.begin()); + }; + const bool by_name = app.help_options_.order == HelpOrder::alphabetical; + std::stable_sort(out.begin(), out.end(), [&](const Listed& a, const Listed& b) { + const auto ra = rank(a.group), rb = rank(b.group); + if (ra != rb) return ra < rb; + return by_name ? a.name < b.name : false; + }); + return out; + } + const App* find_subcommand(std::string_view name) const { for (const auto& sub : subcommands_) if (sub.name_ == name) return ⊂ @@ -452,6 +538,9 @@ private: std::function action_; bool hidden_ = false; std::optional completion_; + std::string group_; + HelpOptions help_options_; + std::string epilogue_; }; // CRTP base: shared transition methods and parent/commit management for OptBuilder & ArgBuilder. @@ -560,6 +649,7 @@ public: SubcommandBuilder& author(std::string_view a) { (void)sub_.author(a); return *this; } SubcommandBuilder& description(std::string_view d) { (void)sub_.description(d); return *this; } SubcommandBuilder& hidden(bool h = true) { (void)sub_.hidden(h); return *this; } + SubcommandBuilder& group(std::string_view g) { (void)sub_.group(g); return *this; } SubcommandBuilder& arg(Arg argument) { (void)sub_.arg(std::move(argument)); return *this; } SubcommandArgBuilder arg(std::string_view name); SubcommandBuilder& option(Option opt) { (void)sub_.option(std::move(opt)); return *this; } @@ -645,10 +735,13 @@ completions::Command snapshot(const App& app) { // there and nowhere below. if (!cmd.version.empty()) cmd.options.emplace_back(detail::Option("version").help("Print version")); - for (const auto& sub : app.subcommands_) - if (!sub.hidden_) cmd.subcommands.emplace_back(snapshot(sub)); - // The command that prints an adapter, as `completion` added it. - if (app.completion_ && !app.completion_->command.empty()) { + // In the order the help lists them (`listed`): the command that prints an + // adapter, as `completion` added it, among them. + for (const auto& c : App::listed(app, true)) { + if (c.sub) { + cmd.subcommands.emplace_back(snapshot(*c.sub)); + continue; + } completions::Command printer; printer.name = app.completion_->command; printer.description = "The completion script for a shell"; diff --git a/tests/cmdline_test.cpp b/tests/cmdline_test.cpp index f4a122e..6fef6e2 100644 --- a/tests/cmdline_test.cpp +++ b/tests/cmdline_test.cpp @@ -601,3 +601,117 @@ TEST(ValueType, BuilderFormAndUncheckedValues) { EXPECT_FALSE(result->value_as("name").has_value()); } + +// ----------------------------------------------------------------------------- +// Help: groups, order, epilogue (0.0.7) +// ----------------------------------------------------------------------------- +static std::string help_of(const App& app) { + testing::internal::CaptureStdout(); + app.print_help("prog"); + return testing::internal::GetCapturedStdout(); +} + +static std::vector names_in_the_snapshot(const App& app) { + std::vector names; + for (const auto& s : snapshot(app).subcommands) names.push_back(s.name); + return names; +} + +// The lines as the help prints them: a heading, a command padded to 12. +static std::string heading(std::string_view name) { return " " + std::string(name) + ":\n"; } +static std::string line(std::string_view name, std::string_view text) { + std::string padded(name); + while (padded.size() < 12) padded += ' '; + return " " + padded + " " + std::string(text) + "\n"; +} +static const std::string completion_line = line("completion", "The completion script for a shell: bash, zsh, fish, powershell"); + +// Nothing asked for: what 0.0.6 printed, the completion command first. +TEST(Help, DeclaredOrderByDefault) { + App app("prog"); + (void)app.completion({.command = "completion", .entry = "__complete"}); + (void)app.subcommand(App("zeta").description("z")).subcommand(App("alpha").description("a")); + EXPECT_NE(help_of(app).find("SUBCOMMANDS:\n" + completion_line + line("zeta", "z") + line("alpha", "a")), + std::string::npos) << help_of(app); +} + +// A group where its first command was declared, by name inside, the completion +// command under its group without moving it, the rest last under the heading given. +TEST(Help, GroupsAndByName) { + App app("prog"); + (void)app.completion({.command = "completion", .entry = "__complete", .group = "OTHER"}); + (void)app.help_options({.order = HelpOrder::alphabetical, .ungrouped = "MORE"}); + (void)app.subcommand(App("config").group("START").description("settings")) + .subcommand(App("zeta").description("z")) + .subcommand(App("auth").group("START").description("accounts")) + .subcommand(App("release").group("WORK").description("releases")) + .subcommand(App("asset").group("WORK").description("assets")) + .subcommand(App("internal").hidden().description("not listed")); + const std::string expected = "SUBCOMMANDS:\n" + heading("START") + line("auth", "accounts") + line("config", "settings") + + heading("WORK") + line("asset", "assets") + line("release", "releases") + + heading("OTHER") + completion_line + + heading("MORE") + line("zeta", "z"); + EXPECT_NE(help_of(app).find(expected), std::string::npos) << help_of(app); + EXPECT_EQ(help_of(app).find("internal"), std::string::npos) << help_of(app); +} + +TEST(Help, DeclaredInsideAGroupAndNoHeadingForTheRest) { + App app("prog"); + (void)app.subcommand(App("zeta").group("A").description("z")) + .subcommand(App("alpha").description("a")) + .subcommand(App("mid").group("A").description("m")); + const std::string expected = "SUBCOMMANDS:\n" + heading("A") + line("zeta", "z") + line("mid", "m") + line("alpha", "a"); + EXPECT_NE(help_of(app).find(expected), std::string::npos) << help_of(app); +} + +// The snapshot hands out the same listing: what a completion offers, and what +// a tool lists from it, is what its help shows. +TEST(Help, TheSnapshotListsTheSameWay) { + App app("prog"); + (void)app.completion({.command = "completion", .entry = "__complete", .group = "TOOLS"}); + (void)app.help_options({.order = HelpOrder::alphabetical}); + (void)app.subcommand(App("zeta").group("B").description("z")) + .subcommand(App("alpha").group("A").description("a")) + .subcommand(App("mid").description("m")) + .subcommand(App("internal").hidden().description("not listed")); + EXPECT_EQ(names_in_the_snapshot(app), (std::vector{"zeta", "alpha", "completion", "mid"})); +} + +// Since 0.0.7 the snapshot leads with the completion command as the help does; +// 0.0.6 appended it. +TEST(Help, TheCompletionCommandLeadsTheSnapshot) { + App app("prog"); + (void)app.completion({.command = "completion", .entry = "__complete"}); + (void)app.subcommand(App("zeta").description("z")).subcommand(App("alpha").description("a")); + EXPECT_EQ(names_in_the_snapshot(app), (std::vector{"completion", "zeta", "alpha"})); +} + +TEST(Help, EpilogueAfterTheCommands) { + App app("prog"); + (void)app.help_epilogue("EXAMPLES:\n $ prog go").subcommand(App("go").description("g")); + EXPECT_NE(help_of(app).find(line("go", "g") + "\nEXAMPLES:\n $ prog go\n"), std::string::npos) << help_of(app); +} + +TEST(Help, AMissingSubcommandIsNamedByTheSameListing) { + App app("prog"); + (void)app.subcommand(App("zeta").group("B").description("z")) + .subcommand(App("alpha").group("A").description("a")) + .subcommand(App("internal").hidden().description("not named")); + testing::internal::CaptureStderr(); + EXPECT_EQ(app.run(Argv{"prog"}), 2); + const std::string err = testing::internal::GetCapturedStderr(); + EXPECT_NE(err.find("prog: a subcommand is required: zeta, alpha\n"), std::string::npos) << err; + EXPECT_EQ(err.find("internal"), std::string::npos) << err; +} + +TEST(Help, TheListingDoesNotTouchTheParse) { + App app("prog"); + int ran = 0; + (void)app.help_options({.order = HelpOrder::alphabetical}) + .subcommand("b").description("b").action([&](const ParsedArgs&) { ran = 1; return 0; }) + .subcommand("a").description("a").end(); + EXPECT_EQ(app.run(Argv{"prog", "b"}), 0); + EXPECT_EQ(ran, 1); + EXPECT_EQ(names_in_the_snapshot(app), (std::vector{"a", "b"})); +} +