diff --git a/.agents/docs/2026-12-05-generic-cli-capabilities-design.md b/.agents/docs/2026-12-05-generic-cli-capabilities-design.md new file mode 100644 index 0000000..d7f67ec --- /dev/null +++ b/.agents/docs/2026-12-05-generic-cli-capabilities-design.md @@ -0,0 +1,81 @@ +# mcpplibs.cmdline 0.3.0:使用者共同需要的命令行能力 —— 子设计 + +- 日期:2026-12-05。状态:**已评审,实现于 0.3.0**(mcpplibs/cmdline 的 PR,每项一个检查点)。 +- 来源:xlings 的生态设计(openxlings/xlings `.agents/docs/2026-11-27-ecosystem-truthful-results-and-architecture-design.md` + §22)。xlings 把命令树改为只用 cmdline 声明(帮助、补全、`--agent-skill-doc` 与核对都从它派生),读它的命令行时 + 发现了库里缺的东西;mcpp(生态设计 §3.9)已用 0.2.0,同类需求它曾在自己的代码里手写。 +- 判据:**一项能力放进 cmdline,当且仅当任何一个用 cmdline 写的命令行都可能需要它,并且实现它不需要知道使用者的领域。** + 只是承载使用者的事实(例如命令的副作用)时,库提供承载的位置,不解释其含义。 +- 兼容:全部是增量。没有选用任何新项时,帮助、补全与快照的输出与 0.2.0 逐字节相同(与 0.0.7 的承诺相同)。 + +## 1. 现状(读 0.2.0 的源码) + +| 使用者需要 | 0.2.0 | 后果 | +|---|---|---| +| 命令别名(xlings:`subos list` 也叫 `ls`,`remove` 也叫 `rm`,`info` 也叫 `i`) | 没有 | 使用者只能在库外维护第二份名字表,帮助与补全看不到它 | +| 渐进显示(xlings:`--help` 只列常用的,`help --all` 再加一层,`--expert` 再加一层) | 只有 `hidden`(全有或全无) | 不常用的选项要么挤满 `--help`,要么完全看不见 | +| 给命令附加使用者的事实(xlings:每个命令的副作用 read、reversible、irreversible、external 与作用的范围,给 agent 读) | 没有 | 只能维护一张按命令路径为键的旁表,即第二份声明 | +| 原样传递的尾部参数(`xlings script <文件> [参数...]`、`exec <名字> <命令...>`) | `-h`/`--help` 在 `--` 之前的任何位置都被截走 | `xlings script x.lua --help` 打印 xlings 的帮助,脚本拿不到 `--help` | +| 未知命令的同义词提示(`uninstall` 对应 `remove`,`add` 对应 `install`) | 只有按编辑距离的相近名字 | 别的工具的动词得不到指向 | +| `help <命令...>` 入口 | 没有;mcpp 在解析前手工改写 | 每个使用者各写一遍 | +| 补全候选带说明、回调知道上下文 | `Candidates` 只返回字符串、只拿到前缀 | xlings 现有的候选带说明(主题、`current` 的含义),迁过来就丢了 | +| 补全协议是可依赖的契约 | `__complete` 与适配器已实现,但文档只写在 api.md 的用法里 | 一个包管理器想为任何用 cmdline 写的程序在安装时生成补全(不运行它),需要协议是稳定的 | + +## 2. 设计 + +1. **命令别名。** 用 `App::alias(name)` 声明,可以多个。解析接受别名,结果里的命令名是规范名 + (`ParsedArgs::subcommand_name()`、`command_path()` 都给规范名)。帮助写成 `list, ls`,补全只给规范名, + 未知命令的相近名字也比较别名。快照的 `Command` 多一个 `aliases`,`agent_skills` 的键用规范名。 + 同一级里别名与另一个名字冲突时,在建树时就报错,并有测试覆盖。 +2. **渐进显示的三级。** 命令与选项都可以设 `level(Level::common | more | expert)`,默认 common。 + - `--help` 只列 common,末尾一行说明还有多少被收起、怎样看。 + - `--help --all` 再列 more,`--help --all --expert` 列全部。只有紧跟 `--help` 时,`--all` 与 `--expert` 才是帮助的修饰; + `--help` 本来就优先于其他词,所以这不会与命令自己的 `--all` 混淆。 + - 层级只影响列出,不影响解析与补全:expert 选项照常可用,补全时排在后面。 + - 快照带上层级,使用者的参考文档可以按层输出。 +3. **注记。** 用 `App::annotate(key, value)` 声明,值是字符串,可以有多个键;选项上也可以加。注记进快照 + (`Command::annotations`),库不解释它们,也不出现在帮助里。`agent_skills::check_options` 多一个 + `required_annotations`:每个可见命令都必须带这些键,否则核对报一行,于是"每个命令都声明了副作用"也成为测试。 +4. **原样传递的尾部参数。** 用 `Arg::trailing()` 声明。落到这个参数的那个词结束选项:其后的词(包括 `--help`、 + `-v`)都是位置参数,等同于在它后面写了 `--`;在它之前,选项照常属于这个命令。两种写法由同一条规则覆盖: + - `tool script [args...]` 把 `file` 声明为 trailing,`tool script x.lua --help` 把 `--help` 交给脚本; + - `tool exec ...` 把 `command` 声明为 trailing,`tool exec box --net none -- make` 里的 + `--net` 仍是 exec 的。 + (实现时改正:初稿写的是"必须是最后一个参数",那样 `script` 的例子做不到。)补全遵守同一条规则。 +5. **未知命令的同义词。** 用 `App::synonyms({{"uninstall", "remove"}, {"agent", "--agent-skill-doc"}})` 声明, + 值是该用的写法。同义词不参与解析:它们不是命令,执行时也不会被当成命令。遇到 `unknown-command` 时, + 如果词在表里,消息写成 + `tool: 'uninstall' is not a command of 'tool'; to do that: tool remove`, + `suggestions` 的第一项是表里的写法,错误代码仍是 `unknown-command`。这只是提示,库不会替人执行。 +6. **`help` 入口。** 用 `HelpOptions::help_command = true` 开启(默认关):`tool help a b` 与 `tool a b --help` 同义, + `tool help` 打印根的帮助;`help` 出现在帮助的列表里。未知的路径按第 5 条与 0.2.0 的相近名字处理。 +7. **补全候选带说明与上下文。** 增加 `Candidates` 的一个重载: + `std::vector(std::string_view prefix, const CompletionContext&)`。`Candidate` 是 `{value, description}`; + `CompletionContext` 给出命令路径和光标前已解析的位置参数与选项。旧签名照常可用。`__complete` 的输出本来就是 + `值说明`,协议不变。 +8. **补全协议成为契约。** 在 `docs/completion-protocol.md` 写明协议版本 1:请求是 `prog <光标前的词...>`; + 回答是每行 `值说明`,最后一行是 `:<指令>`(0 无、1 由 shell 补文件、2 由 shell 补目录);四种 shell 的 + 适配器,以及 `completions::adapter(shell, program, entry)` 给出的就是它们。承诺:协议的不兼容改变使用一个新的 + 入口名,旧入口不变。这样,别的程序(例如包管理器)可以只凭"这个程序用 cmdline 的协议"就为它写出适配器, + 不需要运行它;适配器在补全时才问程序,所以它不随程序的版本变化。 + +9. **应答的选项不需要命令的参数。** `answer_flag` 注册的选项被设置时,它像 `--help` 一样代替命令的参数: + `tool remove --agent-skill-doc` 给出 `remove` 的说明,而不是"required argument 'package' missing"。 + (实现 xlings 时发现:0.2.0 先报缺参数,`--agent-skill-doc` 在任何有必填参数的命令上都答不出来;mcpp 的 `add` 同样如此。) + +## 3. 不放进 cmdline 的 + +- **诊断代码的查询命令(`explain`)。** 诊断代码是应用的语义,cmdline 只拥有自己的用法错误代码,0.2.0 已经让它们带上 + 代码与相近名字。一个应用如果需要按键取嵌入的文本,`agent_skills` 的构建时渲染与按键应答就是这种机制,不需要新功能。 +- **受众模式(agent 模式)、副作用的含义、退出码表。** 都是应用的。库只承载事实(第 3 条),并且已把用法错误固定为退出 2。 +- **把同义词当作别名执行。** 一个有副作用的命令按猜出的名字执行,就是替人做了决定;别名只用于应用自己定义的缩写(第 1 条)。 + +## 4. 测试与发布 + +- 每条都有 `tests/cmdline_test.cpp` 或 `tests/completions_test.cpp` 的用例:别名的解析、帮助与冲突报错;三级显示的 + `--help`、`--help --all`、`--help --all --expert` 输出快照;注记进快照,`required_annotations` 的核对报出缺的命令; + 尾部参数里的 `--help` 原样传入;同义词的消息与 `suggestions`;`help a b` 与 `a b --help` 输出相同;带说明的候选与上下文; + 协议文档中的例子由测试执行,比对输出。 +- 不选用新项时与 0.2.0 相同:现有的快照测试不改一个字节。 +- 一个 PR,每条一个 commit 作为检查点。发布 0.3.0,在 mcpp-index 加 0.2.0 与 0.3.0 的条目(xlings 设计的 M2), + 再由 xlings 使用。mcpp 可按需采用第 1、4、6 条,不需要同步。 diff --git a/README.md b/README.md index 58999b6..9465dff 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,15 @@ an action returns the process status. module (`.skills`) whose `sheet[]` table is in the binary. No header is generated; the developer only imports the module. A runtime filesystem fallback exists (`install_runtime`) but is not recommended for a release. +- **Aliases, levels, annotations (0.3.0)** — `alias("ls")`; `level(Level::more | expert)` lists a + command or option only under `--help --all` (`--expert`); `annotate(key, value)` carries a program's + facts into the snapshot, and `agent_skills::check` can require them on every command. +- **Trailing arguments, synonyms, `help` (0.3.0)** — `Arg::trailing()` ends the options at the word that + fills it; `synonyms({{"uninstall", "remove"}})` turns another tool's verb into a hint, never a run; + `help_options({.help_command = true})` makes `tool help ` the command's help. +- **A completion protocol** — `docs/completion-protocol.md`: what an adapter sends and the program + answers, stable under its entry name, so a package manager can write an adapter without running the + program. - **Build helper** — `mcpp/cmdline/` is a separate build package (`mcpplibs.mplugin.cmdline`), re-exported by this one, so a consumer's `build.mcpp` imports it with no second dependency. It writes a module and adds it with `mcpp::source`; no include path, diff --git a/README.zh.md b/README.zh.md index 8b93f5c..1b5b179 100644 --- a/README.zh.md +++ b/README.zh.md @@ -16,6 +16,12 @@ - **Shell 补全** — `app.completion()`;程序用自己的命令树回答 `__complete`,bash/zsh/fish/PowerShell 适配脚本不含命令表。 - **动作前应答的 flag** — `answer_flag(name, help, fn)`;`parse` → `answer_flags(parsed)` → action。`--help` 仍优先。 - **Agent Skills(可选)** — `agent-skills` feature + `import mcpplibs.cmdline.agent_skills;`。默认构建期:`mcpplibs.mplugin.cmdline` 把 `docs/-skills` 渲染成 C++ module(`.skills`),`sheet[]` 表在二进制里;不生成头文件,开发者只 import module。运行时读取(`install_runtime`)保留,但不推荐用于发布。`agent_skills::check(app, sheets)` 在测试中核对说明与命令树:每个可见的顶层命令都有说明,每份说明都对应一个命令,代码块中的每个例子都能按命令树解析(自 0.2.0)。 +- **别名、层级、注记(0.3.0)** — `alias("ls")`;`level(Level::more | expert)` 让命令或选项只在 `--help --all` + (`--expert`)中列出;`annotate(key, value)` 把程序自己的事实带进快照,`agent_skills::check` 可以要求每个命令都有。 +- **尾部参数、同义词、`help`(0.3.0)** — `Arg::trailing()` 让填入它的那个词结束选项;`synonyms({{"uninstall", "remove"}})` + 把别的工具的动词变成提示,而不是执行;`help_options({.help_command = true})` 让 `tool help <命令>` 成为该命令的帮助。 +- **补全协议** — `docs/completion-protocol.md`:适配器发送什么、程序回答什么,在入口名下保持稳定;包管理器可以不运行程序 + 就为它写出适配器。 - **构建 helper** — `mcpp/cmdline/` 是独立构建包(`mcpplibs.mplugin.cmdline`),由 runtime 包 re-export;消费者的 `build.mcpp` 直接 import,不需要第二条依赖。它写 module 并用 `mcpp::source` 加入构建,不碰 include 路径。 - **C++ Modules** — 库与可选模块都是 module,没有头文件。 diff --git a/docs/api.md b/docs/api.md index 58e84d3..ae0fd6b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -14,7 +14,9 @@ | `Shell` | 目标 shell 枚举:`bash` / `fish` / `zsh` / `powershell` | | `Command` | 命令树快照,补全引擎读取它 | | `CompletionOptions` | 补全的开启方式:可见命令名、隐藏入口、它在 help 里的分组 | -| `HelpOrder` · `HelpOptions` | help 列出子命令的次序与标题(`App::help_options`,见“帮助的列表”) | +| `HelpOrder` · `HelpOptions` | help 列出子命令的次序与标题(`App::help_options`,见“帮助的列表”);`help_command` 开启 `help <命令>`(0.3.0) | +| `Level` | 命令与选项在 help 中的层级:`common` / `more` / `expert`(0.3.0,见“层级、别名、注记与同义词”) | +| `CompletionContext` · `DescribedCandidates` | 带说明的候选与补全所处的位置(0.3.0) | 解析返回 `ParseResult`,即 `std::expected`。`-h`/`--help`、`--version` 时,`ParseError::kind` 分别为 `help` / `version`(补全见“Shell 补全”,为 `completion`),不携带 `message`,通过 `is_error()` 可区分真实错误。 @@ -72,7 +74,32 @@ **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)` `.group(s)`;根命令:`.completion(options)`(见“Shell 补全”) `.help_options(HelpOptions)` `.help_epilogue(s)` +**App**(子命令):`.hidden(bool)` `.group(s)` `.alias(s)` `.level(Level)` `.annotate(k, v)`;任一命令:`.synonyms({{词, 写法}...})`;根命令:`.completion(options)`(见“Shell 补全”) `.help_options(HelpOptions)` `.help_epilogue(s)` + +**Arg** 另有 `.trailing()`,**Option** 另有 `.level(Level)` `.annotate(k, v)`;两者的 `.complete(...)` 也接受 `DescribedCandidates`(0.3.0)。 + +--- + +## 层级、别名、注记与同义词(自 0.3.0) + +- **别名。** `App("list").alias("ls")`:解析接受 `ls`,结果里的命令名是 `list`(`subcommand_name()`、`command_path()`); + help 写成 `list, ls`;补全只给 `list`,但跟随已输入的别名;未知命令的相近名字也比较别名。同一级里一个别名与 + 另一个命令的名字或别名相同,加入时抛出 `std::invalid_argument`。 +- **层级。** `.level(Level::more)`、`.level(Level::expert)`(命令或选项):`--help` 只列 `common`,末尾说明还有多少 + 没列以及怎样看;`--help --all` 加上 `more`,`--help --all --expert` 列全部。解析与补全不受层级影响(补全时 + `expert` 排在后面)。没有用到层级时,help 与 0.2.0 逐字节相同。 +- **注记。** `.annotate("effect", "read")`:进入快照(`Command::annotations`、`Command::annotation(key)`),库不解释、 + help 不打印。`agent_skills::check(..., {.required_annotations = {"effect"}})` 报出缺少某个键的可见命令。 +- **尾部参数。** `Arg("file").trailing()`:落到这个参数的那个词结束选项,其后的词(含 `--help`)都是位置参数; + 在它之前,选项照常属于这个命令。`tool script x.lua --help` 把 `--help` 交给脚本。 +- **同义词。** `.synonyms({{"uninstall", "remove"}})`:这些词不是命令,不被解析成命令;遇到时是 `unknown-command`, + `ParseError::hint` 是该用的写法(`tool remove`),`suggestions` 的第一项是它;`run` 打印 + `tool: to do that: tool remove`。没有任何东西按猜测执行。 +- **`help` 命令。** `help_options({.help_command = true})`:`tool help a b` 与 `tool a b --help` 相同,`--all`、`--expert` + 照样跟随;`help` 列在子命令里,也在快照中(`Command::generated` 为真:库自己加的命令)。 +- **带说明的候选。** `.complete([](std::string_view prefix, const CompletionContext& c) { ... })` 返回 + `std::vector`(值与说明);`c.command` 是已到达的命令(`use`),`c.words` 是光标前的词。 + 补全协议见 [`completion-protocol.md`](completion-protocol.md)。 --- @@ -93,6 +120,7 @@ | `code` | 稳定的代码(自 0.2.0):`unknown-command`、`unknown-option`、`missing-value`、`invalid-value`、`missing-argument`、`invalid-argument`、`empty-command-line`;help、版本与补全时为空 | | `command` | 词所到达的命令,按输入写出(`app sub`);它的 `--help` 适用于这个错误(自 0.2.0) | | `suggestions` | 与未知的名字最相近的已声明名字,最近者在前,至多三个;取自 help 所列的同一份列表,选项带短横线(自 0.2.0) | +| `hint` | 程序给出的该用的写法(`App::synonyms`),整条命令(`tool remove`);没有时为空(自 0.3.0) | | `.is_error()` | `kind == error` 时返回 `true` | ### 用法错误(自 0.2.0) diff --git a/docs/completion-protocol.md b/docs/completion-protocol.md new file mode 100644 index 0000000..1cccb42 --- /dev/null +++ b/docs/completion-protocol.md @@ -0,0 +1,64 @@ +# The completion protocol (version 1) + +A program built with `mcpplibs.cmdline` that calls `App::completion()` answers its own completions. A +shell never holds the program's command tree: its script is an *adapter* of a few lines that passes the +words to the program and lists what comes back. This page is the contract between the two, so that +anything -- a shell, an editor, a package manager writing the adapter at install time -- can rely on it. + +## Request + +``` + ... +``` + +`entry` is `__complete` unless the program chose another (`CompletionOptions::entry`). The words are the +words of the command line after the program's name, up to the cursor; the last is the word being typed, +empty when the cursor stands after a space. The program answers without touching its home, a project or +the network: the answer comes from the command tree and from the candidate callbacks the program +declared. + +## Answer + +One candidate per line, `valuedescription` (no tab when there is no description), then one line +`:`: + +| directive | the shell adds | +|---|---| +| `:0` | nothing: the candidates are the whole answer | +| `:1` | file names | +| `:2` | directory names | + +For a program `tool` with the subcommands `build` ("Build the project", whose `--manifest` names a file) +and `bench` ("Run the benchmarks"), `tool __complete b` answers + +``` +build Build the project +bench Run the benchmarks +:0 +``` + +and `tool __complete build --manifest ""` answers + +``` +:1 +``` + +## Adapters + +`completions::adapter(shell, program, entry)` returns the adapter for `bash`, `zsh`, `fish` or +`powershell`; ` completions ` prints it when the program enables the command. The bash +one starts + +``` +# bash completion for tool: the program answers (`tool __complete `). +``` + +An adapter depends only on the program's name and the entry: a program that gains a command completes it +with the adapter already installed, and a package manager can write the adapter for a program that +declares this protocol without running the program. + +## Stability + +Version 1 is the protocol of cmdline 0.0.6 and later. An incompatible change to the request, the answer or +the directives is made under a new entry name; `__complete` keeps answering version 1. The tests run the +examples on this page (`tests/capabilities_test.cpp`). diff --git a/fixtures/skills/src/main.cpp b/fixtures/skills/src/main.cpp index 41f73f6..e1abe1d 100644 --- a/fixtures/skills/src/main.cpp +++ b/fixtures/skills/src/main.cpp @@ -7,8 +7,9 @@ int main() { using namespace mcpplibs::cmdline; App app("skills-fixture"); App self("self"); - (void)self.subcommand("world").description("the nested world skill"); - (void)app.subcommand("hello").description("say hello"); + (void)self.annotate("effect", "read"); + (void)self.subcommand("world").description("the nested world skill").annotate("effect", "read"); + (void)app.subcommand("hello").description("say hello").annotate("effect", "read"); (void)app.subcommand(std::move(self)); // The table was rendered by build.mcpp; the runtime reads no file. agent_skills::install_default(app, fixture::skills::sheets, @@ -18,7 +19,8 @@ int main() { if (app.run(Argv{"skills-fixture", "--agent-skill-doc"}) != 0) return 3; // The sheets agree with the tree; a sheet that does not is reported. - if (const auto problems = agent_skills::check(app, fixture::skills::sheets, {.ascii_only = true}); + if (const auto problems = agent_skills::check(app, fixture::skills::sheets, + {.ascii_only = true, .required_annotations = {"effect"}}); !problems.empty()) { for (const auto& line : problems) std::println(std::cerr, "{}", line); return 4; @@ -33,5 +35,13 @@ int main() { for (const auto& line : problems) std::println(std::cerr, "{}", line); return 5; } + // A command without the fact every command states is reported (0.3.0). + (void)app.subcommand(App("bare").description("no facts")); + const auto unannotated = agent_skills::check(app, fixture::skills::sheets, + {.exempt = {"bare"}, .required_annotations = {"effect"}}); + if (unannotated.size() != 1 || unannotated.front().find("'skills-fixture bare' has no 'effect' annotation") == std::string::npos) { + for (const auto& line : unannotated) std::println(std::cerr, "{}", line); + return 6; + } return 0; } diff --git a/mcpp.toml b/mcpp.toml index c7c6c31..69917d8 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,7 +1,7 @@ [package] namespace = "mcpplibs" name = "cmdline" -version = "0.2.0" +version = "0.3.0" description = "A simple command-line parsing library/framework for modern C++" license = "Apache-2.0" authors = ["mcpplibs"] diff --git a/src/agent_skills.cppm b/src/agent_skills.cppm index 2654efa..c732124 100644 --- a/src/agent_skills.cppm +++ b/src/agent_skills.cppm @@ -257,6 +257,10 @@ struct check_options { bool ascii_only = false; /// 0: no limit. The build helper enforces its own limit when it renders. std::size_t max_lines = 0; + /// Annotation keys every visible command (the root and the commands the + /// library adds aside) carries (0.3.0, `App::annotate`): a fact the + /// program documents for each command cannot be forgotten for one. + std::vector required_annotations; }; namespace detail { @@ -320,7 +324,21 @@ std::vector check(const App& app, const Sheet (&sheets)[N], check_o const auto tree = snapshot(app); const auto by_key = detail::table(sheets); const std::string name(app.name()); + if (!o.required_annotations.empty()) { + const auto annotated = [&](this const auto& self, const completions::Command& command, const std::string& path) -> void { + for (const auto& sub : command.subcommands) { + if (sub.generated) continue; + const auto key = path.empty() ? sub.name : path + " " + sub.name; + for (const auto& wanted : o.required_annotations) + if (sub.annotation(wanted).empty()) + problems.push_back(std::format("command '{} {}' has no '{}' annotation", name, key, wanted)); + self(sub, key); + } + }; + annotated(tree, ""); + } for (const auto& command : tree.subcommands) { + if (command.generated) continue; if (std::ranges::find(o.exempt, command.name) != o.exempt.end()) continue; if (!by_key.contains(command.name)) problems.push_back(std::format("command '{} {}' has no sheet (docs/{}-skills/{}-{}/SKILL.md)", diff --git a/src/cmdline.cppm b/src/cmdline.cppm index cdd95bb..f84ed5d 100644 --- a/src/cmdline.cppm +++ b/src/cmdline.cppm @@ -54,9 +54,14 @@ export struct HelpOptions { /// a group are listed under `ungrouped`, or `SUBCOMMANDS` when it is empty. /// A command's help with no groups is unchanged. bool groups_as_sections = false; + /// `tool help ...` is `tool ... --help`, and `tool help` + /// the root's help (0.3.0); `help` is listed with the subcommands. Read on + /// the root only. + bool help_command = false; }; export using detail::Arg; export using detail::Option; +export using mcpplibs::cmdline::Level; export using detail::OptionValue; export using detail::ParseError; export using detail::ParseResult; @@ -142,7 +147,8 @@ public: 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_), group_(other.group_), help_options_(other.help_options_), - epilogue_(other.epilogue_), answerers_(other.answerers_) {} + epilogue_(other.epilogue_), answerers_(other.answerers_), aliases_(other.aliases_), level_(other.level_), + annotations_(other.annotations_), synonyms_(other.synonyms_) {} App& operator=(const App& other) { if (this == &other) return *this; name_ = other.name_; @@ -159,6 +165,10 @@ public: help_options_ = other.help_options_; epilogue_ = other.epilogue_; answerers_ = other.answerers_; + aliases_ = other.aliases_; + level_ = other.level_; + annotations_ = other.annotations_; + synonyms_ = other.synonyms_; return *this; } @@ -172,6 +182,35 @@ public: hidden_ = hidden; return *this; } + /// Another name the parse takes for this command (0.3.0): the help lists it + /// beside the name (`list, ls`), the parse reports the name + /// (`subcommand_name()`), a completion offers the name only. A name or an + /// alias two subcommands of one command share is refused when the second + /// is added (`std::invalid_argument`). + [[nodiscard]] App& alias(std::string_view name) { + aliases_.emplace_back(name); + return *this; + } + /// How far into its parent's help this command is listed (0.3.0). + [[nodiscard]] App& level(Level level) { + level_ = level; + return *this; + } + /// A fact of the program's about this command (0.3.0): carried into the + /// snapshot (`Command::annotations`), not interpreted, not printed. + [[nodiscard]] App& annotate(std::string_view key, std::string_view value) { + annotations_.emplace_back(key, value); + return *this; + } + /// Words that are not commands of this one, each with what to type instead + /// (0.3.0): another tool's verb (`uninstall` -> `remove`), a retired + /// command (`agent` -> `--agent-skill-doc`). Not parsed: the word is still + /// an unknown command, and its error says what to do (`ParseError::hint`); + /// nothing runs on the strength of a guess. + [[nodiscard]] App& synonyms(std::vector> words) { + for (auto& w : words) synonyms_.push_back(std::move(w)); + return *this; + } /// Completion, built in (off unless asked for). A shell's adapter calls the /// program with `options.entry` and the words before the cursor; the /// program answers from its command tree, by the rules its parse reads it @@ -225,6 +264,7 @@ public: } [[nodiscard]] OptBuilder option(std::string_view name); [[nodiscard]] App& subcommand(App sub) { + check_names(sub.name_, sub.aliases_); subcommands_.push_back(std::move(sub)); return *this; } @@ -253,6 +293,7 @@ public: Option opt(name); opt.help_ = help; opt.global_ = true; + opt.answered_ = true; options_.push_back(std::move(opt)); answerers_.push_back({std::string(name), std::move(answer)}); return *this; @@ -342,8 +383,18 @@ public: /// The same for the words of a command line, the program name first. int run(std::span args) const { return finish_run(parse_from(args)); } - void print_help(std::string_view program_name = "") const { + void print_help(std::string_view program_name = "") const { print_help(program_name, Level::common); } + + /// The help, listing the options and subcommands at `upto` and below; when + /// some are left out, the last lines say how many and how to see them. + void print_help(std::string_view program_name, Level upto) const { std::string prog = program_name.empty() ? std::string(name_) : std::string(program_name); + std::size_t more = 0, expert = 0; + const auto shown = [&](Level level) { + if (level <= upto) return true; + ++(level == Level::more ? more : expert); + return false; + }; if (!version_.empty()) std::println("{} {}", prog, version_); if (!description_.empty()) std::println("\n{}\n", description_); std::println("USAGE:"); @@ -353,6 +404,7 @@ public: if (!options_.empty()) { std::println("\nOPTIONS:"); for (const auto& opt : options_) { + if (!shown(opt.level_)) continue; std::string opt_str; if (opt.short_) opt_str += std::format("-{}, ", opt.short_); if (!opt.long_name.empty()) opt_str += "--" + opt.long_name; @@ -364,7 +416,8 @@ public: } const bool listsCompletion = completion_ && !completion_->command.empty() && (program_name.empty() || program_name == name_); - const auto commands = listed(*this, listsCompletion); + auto commands = listed(*this, listsCompletion); + std::erase_if(commands, [&](const Listed& c) { return c.sub && !shown(c.sub->level_); }); if (!commands.empty()) { const bool any_group = std::ranges::any_of(commands, [](const Listed& c) { return !c.group.empty(); }); if (!help_options_.groups_as_sections || !any_group) { @@ -376,7 +429,7 @@ public: if (!under.empty()) std::println(" {}:", under); heading = under; } - std::string padded(c.name); + std::string padded = c.label(); while (padded.size() < 12) padded += ' '; std::println(" {} {}", padded, c.description); } @@ -392,13 +445,17 @@ public: std::println("\n{}:", under); heading = under; } - std::string padded(c.name); + std::string padded = c.label(); while (padded.size() < 12) padded += ' '; std::println(" {} {}", padded, c.description); } } } if (!epilogue_.empty()) std::print("\n{}{}", epilogue_, epilogue_.ends_with('\n') ? "" : "\n"); + // What was left out, and the words that list it. Nothing when every + // option and command is listed: a tree with no levels prints as 0.2.0. + if (more) std::println("\n{} more not listed: '{} --help --all'", more, prog); + if (expert) std::println("{}{} for experts not listed: '{} --help --all --expert'", more ? "" : "\n", expert, prog); } [[nodiscard]] std::string completions(Shell shell) const; @@ -429,6 +486,17 @@ private: return std::unexpected(ParseError::make_completion()); } } + // `help ...` (HelpOptions::help_command): the command's words, + // then `--help`, then what modifies a help (`--all`, `--expert`). + std::vector rewritten; + if (help_options_.help_command && !tokens.empty() && tokens[0] == "help") { + for (const auto word : tokens.subspan(1)) + if (!word.starts_with('-')) rewritten.push_back(word); + rewritten.emplace_back("--help"); + for (const auto word : tokens.subspan(1)) + if (word.starts_with('-')) rewritten.push_back(word); + tokens = rewritten; + } global_keys_t global_keys; global_opts_t global_opts; std::vector