From 0958eabdfbee32c43152f6f37de7ecd2637c4db7 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Fri, 4 Dec 2026 00:08:07 +0900 Subject: [PATCH 01/10] feat(0.1.0): flags answered before actions, grouped help sections, the Agent Skills module and build helper - answer_flag/answer_flags: a global flag answered after the parse and before any action; --help keeps its precedence. - HelpOptions.groups_as_sections: a group is a top-level section, not a second-level heading. - mcpplibs.cmdline.agent_skills (feature agent-skills): --agent-skill-doc reads frontmatter-stripped bodies and appends the root/self index. - mcpp/cmdline: mcpplibs.mplugin.cmdline, a host-module package that scans docs/-skills, validates the Agent Skills format, normalizes line endings and writes a deterministic sheet[] header; the runtime package re-exports it. - mcpp only: xmake files and documentation removed; README is English with README.zh.md; CI runs Linux, macOS and Windows and builds the fixture. - version 0.1.0. --- .github/workflows/ci.yml | 31 +- .gitignore | 1 - .xlings.json | 2 +- README.md | 209 ++++------- README.zh.md | 90 +++++ examples/xmake.lua | 20 - fixtures/skills/build.mcpp | 8 + .../skills-fixture-hello/SKILL.md | 6 + .../skills-fixture-self-world/SKILL.md | 6 + .../skills-fixture/SKILL.md | 8 + fixtures/skills/mcpp.toml | 10 + fixtures/skills/src/main.cpp | 21 ++ mcpp.toml | 28 +- mcpp/cmdline/mcpp.toml | 28 ++ mcpp/cmdline/src/skills.cppm | 352 ++++++++++++++++++ src/agent_skills.cppm | 164 ++++++++ src/cmdline.cppm | 90 ++++- src/parse.cppm | 11 + tests/cmdline_test.cpp | 72 ++++ tests/xmake.lua | 18 - xmake.lua | 11 - 21 files changed, 978 insertions(+), 208 deletions(-) create mode 100644 README.zh.md delete mode 100644 examples/xmake.lua create mode 100644 fixtures/skills/build.mcpp create mode 100644 fixtures/skills/docs/skills-fixture-skills/skills-fixture-hello/SKILL.md create mode 100644 fixtures/skills/docs/skills-fixture-skills/skills-fixture-self-world/SKILL.md create mode 100644 fixtures/skills/docs/skills-fixture-skills/skills-fixture/SKILL.md create mode 100644 fixtures/skills/mcpp.toml create mode 100644 fixtures/skills/src/main.cpp create mode 100644 mcpp/cmdline/mcpp.toml create mode 100644 mcpp/cmdline/src/skills.cppm create mode 100644 src/agent_skills.cppm delete mode 100644 tests/xmake.lua delete mode 100644 xmake.lua diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 28c7383..8c5bdb4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,8 +10,15 @@ env: jobs: build: - name: build + test (linux x86_64, mcpp) - runs-on: ubuntu-latest + name: build + test (${{ matrix.os }}, mcpp) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-15, windows-2025] + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash steps: - uses: actions/checkout@v4 @@ -30,17 +37,19 @@ jobs: sleep 30 done - # Cache mcpp's self-bootstrapped sandbox (toolchain, binutils, ninja, - # patchelf). The toolchain set is pinned by the mcpp in .xlings.json, - # so its version keys the cache. - - name: Cache mcpp sandbox - uses: actions/cache@v4 - with: - path: ~/.xlings/data/xpkgs/xim-x-mcpp/2026.11.8.1/registry - key: mcpp-sandbox-${{ runner.os }}-mcpp2026.11.8.1 - - name: Build with mcpp run: mcpp build + - name: Build the optional agent-skills module + run: mcpp build --features agent-skills + - name: Run tests run: mcpp test + + # The build helper is a package of its own; this fixture proves the + # re-export, the standard layout and the generated header on all three. + - name: Build the skills fixture + run: | + cd fixtures/skills + mcpp build + ./target/*/bin/skills-fixture* diff --git a/.gitignore b/.gitignore index c710f1b..380e453 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -.xmake build target .xlings/subos/ diff --git a/.xlings.json b/.xlings.json index e044bb3..3eecbc7 100644 --- a/.xlings.json +++ b/.xlings.json @@ -1,5 +1,5 @@ { "workspace": { - "mcpp": "2026.11.8.1" + "mcpp": "2026.11.27.1" } } diff --git a/README.md b/README.md index 2ba6165..eaa1dba 100644 --- a/README.md +++ b/README.md @@ -1,162 +1,103 @@ # cmdline -> 一个简单易用的命令行解析库/框架 - `import mcpplibs.cmdline;` - -使用 C++23 模块的类型安全命令行解析库。流式链式接口,零样板代码。支持位置参数、短/长选项、子命令、全局标志,以及基于 `std::expected` 的错误处理。 - -## ✨ 特性 - -- **C++23 模块** — `import mcpplibs.cmdline` - -- **流式接口** — 链式构建方法,所见即所得的 API - -- **子命令** — 任意层级的嵌套命令,`action` 回调分发或手动分发 - -- **退出码** — `action` 可返回 `int`,`run` 返回该退出码;解析错误写入标准错误并返回 2 - -- **全局选项** — 标志透明地传播到所有子命令 - -- **类型安全结果** — `std::expected` - -- **多种解析模式** — 支持 `argc/argv`、`cmdline::Argv`(即 `vector`)或原始 `string_view` +> A small, type-safe command-line parser for C++23 modules — `import mcpplibs.cmdline;` + +[中文](README.zh.md) | English + +Declare a command tree once; the parser, help, completions and the per-command dispatch read +the same declarations. Arguments and option values are checked where they are declared, and +an action returns the process status. + +## Features + +- **C++23 module** — one import, no headers. +- **Subcommands at any depth** — an `action` gets its own `ParsedArgs`; a command without one + leaves the run to its nearest ancestor. +- **Global options** — a flag parses at any depth and is copied into the parse. +- **Checked values** — `values({...})` is a closed set; `value_type()` checks a number with + `std::from_chars`; `value_as()` reads it back. +- **Help that is a list** — `.group()` headings, `.help_options({.order, .ungrouped, + .groups_as_sections})`, `.help_epilogue()`; the help, the completion candidates and the + "a subcommand is required" message agree. +- **Shell completions** — `app.completion()`; the program answers `__complete` from its own tree, + and the bash/zsh/fish/PowerShell adapters carry no command list. +- **Flags answered before the action** — `answer_flag(name, help, fn)`; `parse` → + `answer_flags(parsed)` → the action. `--help` still wins. +- **Agent Skills (optional)** — `agent-skills` feature + `import mcpplibs.cmdline.agent_skills;` + answers `--agent-skill-doc` from sheets a build program embeds; do not install it and the flag + does not exist. +- **Build helper** — `mcpp/cmdline/` is a separate build package + (`mcpplibs.mplugin.cmdline`), re-exported by this one: `build.mcpp` imports it and embeds + `docs/-skills` as a `sheet[]` table. One function, or every path/limit overridden. + +## Requirements + +C++23 modules and [mcpp](https://github.com/mcpp-community/mcpp). There is no xmake path. + +## Build and test + +```sh +mcpp build +mcpp test +mcpp build --features agent-skills # the optional runtime module +``` -- **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、补全候选与“缺子命令”的报错用同一份列表 +The library's own tests are gtest cases under `tests/`; `fixtures/skills` is a small program that +builds a `sheet[]` table and answers it. -## 快速开始 +## A program ```cpp import std; import mcpplibs.cmdline; -using namespace mcpplibs; +using namespace mcpplibs::cmdline; int main(int argc, char* argv[]) { - auto app = cmdline::App("myapp") - .version("1.0.0") - .description("A demo CLI") - .arg("input").required().help("输入文件") - .option("verbose").short_name('v').help("详细输出") - .option("config").short_name('c').takes_value().value_name("FILE").help("配置文件") - .action([](const cmdline::ParsedArgs& p) { - if (p.is_flag_set("verbose")) std::println("详细模式已开启"); - if (auto c = p.value("config")) std::println("配置文件: {}", *c); - std::println("输入文件: {}", p.positional(0)); - }); - + App app("hello"); + app.version("1.0.0") + .description("say hello") + .option("name").short_name('n').takes_value().value_name("NAME").help("who to greet") + .action([](const ParsedArgs& p) { + std::println("hello, {}", p.value("name").value_or("world")); + }); return app.run(argc, argv); } ``` -### 子命令 + action / run +Two sections, each command one line: ```cpp -auto app = cmdline::App("demo") - .version("0.1.0") - .description("Demo: subcommands with action dispatch") - .option("yes").short_name('y').global().help("自动确认") - .subcommand("add") - .description("添加目标") - .arg("target").required() - .arg("version").required() - .action([](const cmdline::ParsedArgs& a) { - std::println("add: {}@{}", a.value("target").value_or(""), - a.value("version").value_or("")); - }) - .subcommand("remove") - .description("移除目标") - .arg("target").required() - .action([](const cmdline::ParsedArgs& a) { std::println("remove: {}", a.positional(0)); }); - -app.run(argc, argv); +App app("tool"); +app.help_options({.order = HelpOrder::alphabetical, .groups_as_sections = true}); +app.subcommand(App("run").group("SUBCOMMANDS").description("run a job")); +app.subcommand(App("self").group("SELF MANAGEMENT").description("manage the tool")); ``` -### 多种解析模式 +`--agent-skill-doc` on a build-program-generated table: ```cpp -auto r1 = app.parse(argc, argv); -auto r2 = app.parse_from(cmdline::Argv{"myapp", "add", "x", "1.0"}); -auto r3 = app.parse_from("myapp remove x --yes"); +// build.mcpp +import mcpplibs.mplugin.cmdline; +int main() { return mcpplibs::mplugin::cmdline::embed_default() ? 0 : 1; } ``` -### 数值选项 - -```cpp -auto app = cmdline::App("myapp") - .option(cmdline::Option("rate").value_type().help("每秒多少片")) - .option(cmdline::Option("frames").short_name('f').value_type()); -// myapp --rate fast → 解析错误:"option --rate takes a number, not `fast`" -auto parsed = app.parse(argc, argv); -const double rate = parsed->value_as("rate").value_or(30.0); // 缺省时为空 -``` - -## 构建 - -**使用 xmake** - -```shell -xmake # 构建库 -xmake run basic # 运行基础示例 -xmake -y run cmdline_test # 运行测试(自动安装 gtest) -``` - -**使用 mcpp** - -```shell -mcpp build # 构建库 -mcpp test # 运行 tests/ 下的测试 -``` - -## 集成到构建工具 - -### xmake - -```lua --- 添加 mcpplibs 包仓库 -add_repositories("mcpplibs-index https://github.com/mcpplibs/mcpplibs-index.git") - --- 添加依赖 -add_requires("cmdline") - -target("mytool") - set_kind("binary") - set_languages("c++23") - add_files("main.cpp") - add_packages("cmdline") - set_policy("build.c++.modules", true) -``` - -### mcpp - -#### 添加依赖 - -```bash -mcpp add cmdline@0.0.2 -``` - -或在 `mcpp.toml` 中手动添加: - -```toml -[dependencies] -cmdline = "0.0.2" -``` - -#### 构建 - -```bash -mcpp build -``` - -#### 代码示例 - ```cpp +// src/skills.cppm +module; +#include "sheets.h" +export module myapp.skills; import mcpplibs.cmdline; -// ... 参见上方"快速开始" +import mcpplibs.cmdline.agent_skills; + +export void install(mcpplibs::cmdline::App& app) { + mcpplibs::cmdline::agent_skills::install_default(app, myapp::skills::sheets, + {.root_commands = {"run", "self"}, .self_commands = {"version"}}); +} ``` -## 相关链接 +## Documentation -- [社区官网](https://mcpp.d2learn.org) -- [社区论坛](https://forum.d2learn.org/category/20) ([`Q: 1067245099`](https://qm.qq.com/q/nBQdBaYNna)) -- [mcpp开源主页](https://github.com/mcpp-community) +- [`docs/api.md`](docs/api.md) — the API, option by option. +- [`examples/`](examples) — programs to copy. +- [`LICENSE`](LICENSE) — Apache-2.0. diff --git a/README.zh.md b/README.zh.md new file mode 100644 index 0000000..87dab6e --- /dev/null +++ b/README.zh.md @@ -0,0 +1,90 @@ +# cmdline + +> 一个小而类型安全的 C++23 命令行解析库 — `import mcpplibs.cmdline;` + +[English](README.md) | 中文 + +命令树只声明一次;解析、help、补全和分发读同一份声明。参数与选项值在声明处校验,action 返回进程退出码。 + +## 特性 + +- **C++23 module** — 一个 import,没有头文件。 +- **任意层级的子命令** — `action` 拿到自己的 `ParsedArgs`;没有 action 的命令交给最近的祖先。 +- **全局选项** — 任意层级都能解析,并合并进解析结果。 +- **校验过的值** — `values({...})` 是闭集;`value_type()` 用 `std::from_chars` 校验数字;`value_as()` 读回。 +- **help 就是列表** — `.group()` 标题、`.help_options({.order, .ungrouped, .groups_as_sections})`、`.help_epilogue()`;help、补全候选和“缺子命令”的报错一致。 +- **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;`,从构建期嵌入的 sheets 回答 `--agent-skill-doc`;不安装就没有这个 flag。 +- **构建 helper** — `mcpp/cmdline/` 是独立构建包(`mcpplibs.mplugin.cmdline`),由 runtime 包 re-export:`build.mcpp` 引入它,把 `docs/-skills` 嵌成 `sheet[]`。一个函数开启,路径/上限都可覆盖。 + +## 要求 + +C++23 modules 与 [mcpp](https://github.com/mcpp-community/mcpp)。不再提供 xmake。 + +## 构建与测试 + +```sh +mcpp build +mcpp test +mcpp build --features agent-skills # 可选的运行时模块 +``` + +库的测试是 `tests/` 下的 gtest 用例;`fixtures/skills` 是一个小程序,构建 `sheet[]` 表并回答它。 + +## 一个程序 + +```cpp +import std; +import mcpplibs.cmdline; + +using namespace mcpplibs::cmdline; + +int main(int argc, char* argv[]) { + App app("hello"); + app.version("1.0.0") + .description("say hello") + .option("name").short_name('n').takes_value().value_name("NAME").help("who to greet") + .action([](const ParsedArgs& p) { + std::println("hello, {}", p.value("name").value_or("world")); + }); + return app.run(argc, argv); +} +``` + +两个 section,每条命令一句话: + +```cpp +App app("tool"); +app.help_options({.order = HelpOrder::alphabetical, .groups_as_sections = true}); +app.subcommand(App("run").group("SUBCOMMANDS").description("run a job")); +app.subcommand(App("self").group("SELF MANAGEMENT").description("manage the tool")); +``` + +`--agent-skill-doc` 与构建期表: + +```cpp +// build.mcpp +import mcpplibs.mplugin.cmdline; +int main() { return mcpplibs::mplugin::cmdline::embed_default() ? 0 : 1; } +``` + +```cpp +// src/skills.cppm +module; +#include "sheets.h" +export module myapp.skills; +import mcpplibs.cmdline; +import mcpplibs.cmdline.agent_skills; + +export void install(mcpplibs::cmdline::App& app) { + mcpplibs::cmdline::agent_skills::install_default(app, myapp::skills::sheets, + {.root_commands = {"run", "self"}, .self_commands = {"version"}}); +} +``` + +## 文档 + +- [`docs/api.md`](docs/api.md) — API。 +- [`examples/`](examples) — 可复制的示例。 +- [`LICENSE`](LICENSE) — Apache-2.0。 diff --git a/examples/xmake.lua b/examples/xmake.lua deleted file mode 100644 index 5d0f654..0000000 --- a/examples/xmake.lua +++ /dev/null @@ -1,20 +0,0 @@ -add_rules("mode.debug", "mode.release") -set_languages("c++23") - -target("basic") - set_kind("binary") - add_files("basic.cpp") - add_deps("cmdline") - set_policy("build.c++.modules", true) - -target("with_dispatch") - set_kind("binary") - add_files("with_dispatch.cpp") - add_deps("cmdline") - set_policy("build.c++.modules", true) - -target("parse_from_string") - set_kind("binary") - add_files("parse_from_string.cpp") - add_deps("cmdline") - set_policy("build.c++.modules", true) diff --git a/fixtures/skills/build.mcpp b/fixtures/skills/build.mcpp new file mode 100644 index 0000000..119c4c7 --- /dev/null +++ b/fixtures/skills/build.mcpp @@ -0,0 +1,8 @@ +import std; +import mcpplibs.mplugin.cmdline; + +int main() { + mcpplibs::mplugin::cmdline::options o; + o.name_space = "fixture::skills"; // the generated table's namespace + return mcpplibs::mplugin::cmdline::embed(o) ? 0 : 1; +} diff --git a/fixtures/skills/docs/skills-fixture-skills/skills-fixture-hello/SKILL.md b/fixtures/skills/docs/skills-fixture-skills/skills-fixture-hello/SKILL.md new file mode 100644 index 0000000..5af9e2b --- /dev/null +++ b/fixtures/skills/docs/skills-fixture-skills/skills-fixture-hello/SKILL.md @@ -0,0 +1,6 @@ +--- +name: skills-fixture-hello +description: Say hello. +--- + +Say hello, then stop. diff --git a/fixtures/skills/docs/skills-fixture-skills/skills-fixture-self-world/SKILL.md b/fixtures/skills/docs/skills-fixture-skills/skills-fixture-self-world/SKILL.md new file mode 100644 index 0000000..eb2c1d7 --- /dev/null +++ b/fixtures/skills/docs/skills-fixture-skills/skills-fixture-self-world/SKILL.md @@ -0,0 +1,6 @@ +--- +name: skills-fixture-self-world +description: The nested world skill. +--- + +A nested skill. diff --git a/fixtures/skills/docs/skills-fixture-skills/skills-fixture/SKILL.md b/fixtures/skills/docs/skills-fixture-skills/skills-fixture/SKILL.md new file mode 100644 index 0000000..6c3f5de --- /dev/null +++ b/fixtures/skills/docs/skills-fixture-skills/skills-fixture/SKILL.md @@ -0,0 +1,8 @@ +--- +name: skills-fixture +description: The fixture's root skill. +--- + +# Fixture + +Run the hello skill. diff --git a/fixtures/skills/mcpp.toml b/fixtures/skills/mcpp.toml new file mode 100644 index 0000000..58c9877 --- /dev/null +++ b/fixtures/skills/mcpp.toml @@ -0,0 +1,10 @@ +[package] +name = "skills-fixture" +version = "0.1.0" + +[dependencies] +cmdline = { path = "../..", features = ["agent-skills"] } + +[targets.skills-fixture] +kind = "bin" +main = "src/main.cpp" diff --git a/fixtures/skills/src/main.cpp b/fixtures/skills/src/main.cpp new file mode 100644 index 0000000..867d1f1 --- /dev/null +++ b/fixtures/skills/src/main.cpp @@ -0,0 +1,21 @@ +#include "sheets.h" + +#include + +import mcpplibs.cmdline; +import mcpplibs.cmdline.agent_skills; + +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)app.subcommand(std::move(self)); + agent_skills::install_default(app, fixture::skills::sheets, + {.root_commands = {"hello", "self"}, .self_commands = {"world"}}); + if (app.run(Argv{"skills-fixture", "hello", "--agent-skill-doc"}) != 0) return 1; + if (app.run(Argv{"skills-fixture", "self", "world", "--agent-skill-doc"}) != 0) return 2; + if (app.run(Argv{"skills-fixture", "--agent-skill-doc"}) != 0) return 3; + return fixture::skills::sheets_size == 3 ? 0 : 4; +} diff --git a/mcpp.toml b/mcpp.toml index fafa847..649822b 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -1,7 +1,7 @@ [package] namespace = "mcpplibs" name = "cmdline" -version = "0.0.7" +version = "0.1.0" description = "A simple command-line parsing library/framework for modern C++" license = "Apache-2.0" authors = ["mcpplibs"] @@ -10,5 +10,31 @@ repo = "https://github.com/mcpplibs/cmdline" [targets.cmdline] kind = "lib" +# The command tree, the parse, and help; no build system is involved. +[build] +sources = [ + "src/cmdline.cppm", + "src/complete.cppm", + "src/completions.cppm", + "src/options.cppm", + "src/parse.cppm", +] + +[features] +default = [] + +# The Agent Skills convention of --agent-skill-doc (module +# mcpplibs.cmdline.agent_skills): opt-in, so a CLI that does not use it +# links neither the module nor the flag. The sheets themselves are built by +# mcpp/mcpplibs.mplugin.cmdline, re-exported by this package. +[features.agent-skills] +sources = ["src/agent_skills.cppm"] + +# The build helper (module mcpplibs.mplugin.cmdline) lives in mcpp/cmdline/ as +# its own package; this re-export is what lets a consumer's build.mcpp import +# it with no second dependency, the shape slint-m uses for its rule. +[build-dependencies] +mcpplibs.mplugin.cmdline = { path = "mcpp/cmdline", host-module = true, reexport = true } + [dev-dependencies] gtest = "1.15.2" diff --git a/mcpp/cmdline/mcpp.toml b/mcpp/cmdline/mcpp.toml new file mode 100644 index 0000000..2744b4f --- /dev/null +++ b/mcpp/cmdline/mcpp.toml @@ -0,0 +1,28 @@ +# mcpplibs.mplugin.cmdline — the Agent Skills build helper of mcpplibs.cmdline. +# +# A build program imports the module (the runtime package re-exports this +# package, so a consumer only depends on `cmdline`): +# +# import mcpp; +# import mcpplibs.mplugin.cmdline; +# int main() { return mcpplibs::mplugin::cmdline::embed_default() ? 0 : 1; } +# +# It reads markdown and writes a `sheet[]` header: no translation unit, no +# compiler rule, no command tree. Host module only: this package is never +# linked into a program. +[package] +namespace = "mcpplibs.mplugin" +name = "cmdline" +version = "0.1.0" +standard = "c++23" +description = "The Agent Skills build helper of mcpplibs.cmdline: scan, validate and embed docs/-skills as a sheet[] header" +license = "Apache-2.0" +authors = ["mcpplibs"] +repo = "https://github.com/mcpplibs/cmdline" +platforms = ["linux", "macos", "windows"] + +[targets.cmdline] +kind = "lib" + +[build] +sources = ["src/skills.cppm"] diff --git a/mcpp/cmdline/src/skills.cppm b/mcpp/cmdline/src/skills.cppm new file mode 100644 index 0000000..9066eaa --- /dev/null +++ b/mcpp/cmdline/src/skills.cppm @@ -0,0 +1,352 @@ +// mcpplibs.mplugin.cmdline — the build-time half of the Agent Skills +// convention: scan a repository's skills, validate them, normalize line +// endings, and write one `sheet[]` header the runtime helper answers from. +// +// It is a build program's import (a host module), not a compiler rule: it +// generates DATA, never a command tree or an action. The default layout is +// documented in the design (`docs/-skills//SKILL.md` and +// `docs/-skills/-/SKILL.md`); every part of it is an +// `options` field. +export module mcpplibs.mplugin.cmdline; + +import std; +import mcpp; + +export namespace mcpplibs::mplugin::cmdline { + +/// Everything `embed` may vary. The defaults are the standard layout: an app +/// called `gitany` reads `docs/gitany-skills/gitany/SKILL.md` and the sibling +/// `gitany-/SKILL.md`, under the manifest directory, and writes +/// `sheets.h` into `target/`. An absent standard directory falls back to the +/// manifest's `AGENTS.md` as a root-only skill, unless `fallback_agents` is +/// false. +struct options { + std::string root; // empty: docs/-skills + std::string app; // empty: mcpp::package_name() + bool standard_layout = true; // false: directory names are keys (or `key` decides) + bool fallback_agents = true; // AGENTS.md when the standard directory is absent + std::size_t max_lines = 100; // 0: no limit + std::string out_dir; // empty: /include/mcpp.mplugin.cmdline + std::string name_space; // empty: ::skills + std::string identifier = "sheets"; // the array's name; the header is .h + std::string row_type = "sheet"; // {key, data, size} + std::string key_suffix; // appended to every derived key; gitany uses ".md" + std::function key; // skill directory -> key; empty: ask the layout +}; + +namespace detail { + +namespace fs = std::filesystem; + +inline bool name_ok(std::string_view name) { + if (name.empty() || name == "." || name == "..") return false; + for (const char c : name) + if (!(std::isalnum(static_cast(c)) || c == '.' || c == '_' || c == '-')) + return false; + return true; +} + +inline std::string trim(std::string_view text) { + const auto first = text.find_first_not_of(" \t"); + const auto last = text.find_last_not_of(" \t\r"); + return first == std::string_view::npos ? std::string{} : std::string(text.substr(first, last - first + 1)); +} + +// UTF-8 BOM removed, CRLF and a bare CR normalized to LF. A skill is text; a +// checkout's line endings are not part of what it says. +inline std::optional read_text(const fs::path& file, std::string& error) { + std::ifstream in(file, std::ios::binary); + if (!in) { + error = "cannot read " + file.generic_string(); + return std::nullopt; + } + std::string bytes{std::istreambuf_iterator(in), std::istreambuf_iterator()}; + if (bytes.starts_with("\xEF\xBB\xBF")) bytes.erase(0, 3); + std::string text; + text.reserve(bytes.size()); + for (std::size_t i = 0; i < bytes.size(); ++i) { + if (bytes[i] == '\r') { + if (i + 1 < bytes.size() && bytes[i + 1] == '\n') continue; // the LF follows + text.push_back('\n'); + } else { + text.push_back(bytes[i]); + } + } + return text; +} + +inline std::size_t line_count(const std::string& text) { + if (text.empty()) return 0; + const auto newlines = static_cast(std::ranges::count(text, '\n')); + return newlines + (text.ends_with('\n') ? 0 : 1); +} + +struct frontmatter { + std::string name; + std::string description; +}; + +inline std::optional read_frontmatter(const std::string& text) { + if (!text.starts_with("---\n")) return std::nullopt; + const auto end = text.find("\n---\n", 4); + if (end == std::string::npos) return std::nullopt; + frontmatter out; + for (std::size_t i = 4; i < end;) { + const auto eol = text.find('\n', i); + const auto stop = eol == std::string::npos ? end : std::min(eol, end); + const std::string_view line(text.data() + i, stop - i); + i = stop + 1; + const auto colon = line.find(':'); + if (colon == std::string_view::npos) continue; + const auto key = trim(line.substr(0, colon)); + const auto value = trim(line.substr(colon + 1)); + if (key == "name") out.name = value; + else if (key == "description") out.description = value; + } + return out; +} + +inline std::string_view body(std::string_view skill) { + if (!skill.starts_with("---\n")) return skill; + const auto end = skill.find("\n---\n", 4); + if (end == std::string_view::npos) return skill; + const auto rest = skill.substr(end + 5); + const auto first = rest.find_first_not_of('\n'); + return first == std::string_view::npos ? std::string_view{} : rest.substr(first); +} + +inline bool inside(const fs::path& root, const fs::path& candidate) { + std::error_code ec; + const auto parent = fs::weakly_canonical(root, ec); + if (ec) return false; + const auto child = fs::weakly_canonical(candidate, ec); + if (ec) return false; + const auto parent_text = parent.generic_string(); + const auto child_text = child.generic_string(); + return child_text == parent_text + || (child_text.size() > parent_text.size() + && child_text.compare(0, parent_text.size(), parent_text) == 0 + && (parent_text.ends_with('/') || child_text[parent_text.size()] == '/')); +} + +inline bool write_if_different(const fs::path& file, std::string_view text, std::string& error) { + std::error_code ec; + if (fs::is_regular_file(file, ec)) { + std::ifstream in(file, std::ios::binary); + std::string old{std::istreambuf_iterator(in), std::istreambuf_iterator()}; + if (old == text) return true; + } + fs::create_directories(file.parent_path(), ec); + std::ofstream out(file, std::ios::binary | std::ios::trunc); + out.write(text.data(), static_cast(text.size())); + if (!out) { + error = "cannot write " + file.generic_string(); + return false; + } + return true; +} + +struct skill { + std::string key; + std::string directory; + std::string text; + fs::path input; +}; + +inline std::string key_for(const options& opt, std::string_view app, std::string_view directory, std::string& error) { + std::string key; + if (opt.key) key = opt.key(directory); + if (key.empty()) { + if (!opt.standard_layout) key = std::string(directory); + else if (directory == app) key = "root"; + else { + const std::string prefix = std::string(app) + "-"; + if (!directory.starts_with(prefix)) { + error = std::format("skill directory '{}' does not start with '{}' (standard layout)", directory, prefix); + return {}; + } + const auto suffix = std::string(directory.substr(prefix.size())); + key = suffix.starts_with("self-") ? "self." + suffix.substr(5) : suffix; + } + } + return key + opt.key_suffix; +} + +inline std::string header_text(const options& opt, std::string_view app, const std::vector& skills) { + const std::string ns = opt.name_space.empty() ? std::string(app) + "::skills" : opt.name_space; + std::string text = "// Generated by mcpplibs.mplugin.cmdline from "; + text += std::to_string(skills.size()); + text += " skill(s). Do not edit.\n#pragma once\n\n#include \n\n"; + text += "namespace " + ns + " {\n\n"; + text += "struct " + opt.row_type + " {\n const char* key;\n const unsigned char* data;\n std::size_t size;\n};\n\n"; + for (std::size_t i = 0; i < skills.size(); ++i) { + const auto& bytes = skills[i].text; + text += "inline constexpr unsigned char " + opt.identifier + "_" + std::to_string(i) + "[] = {"; + for (std::size_t j = 0; j < bytes.size(); ++j) { + if (j % 16 == 0) text += "\n "; + text += std::format("0x{:02x},", static_cast(static_cast(bytes[j]))); + if (j + 1 < bytes.size()) text += ' '; + } + text += "\n};\n\n"; + } + text += "inline constexpr " + opt.row_type + " " + opt.identifier + "[] = {\n"; + for (std::size_t i = 0; i < skills.size(); ++i) + text += " {\"" + skills[i].key + "\", " + opt.identifier + "_" + std::to_string(i) + ", " + + std::to_string(skills[i].text.size()) + "},\n"; + text += "};\n\ninline constexpr std::size_t " + opt.identifier + "_size = " + std::to_string(skills.size()) + + ";\n\n} // namespace " + ns + "\n"; + return text; +} + +} // namespace detail + +/// Scan, validate and embed. Returns false and writes the reason to stderr when +/// the layout is broken or a skill is not the Agent Skills format. +inline bool embed(const options& opt) { + using namespace detail; + const fs::path manifest = mcpp::manifest_dir(); + const std::string app = opt.app.empty() ? std::string(mcpp::package_name()) : opt.app; + if (!name_ok(app)) { + std::cerr << "mcpplibs.mplugin.cmdline: no app name (set options::app or package.name)\n"; + return false; + } + const fs::path root = opt.root.empty() + ? manifest / "docs" / (app + "-skills") + : (fs::path(opt.root).is_absolute() ? fs::path(opt.root) : manifest / opt.root); + + std::vector skills; + std::string error; + + if (fs::is_directory(root)) { + const fs::path root_skill = root / app / "SKILL.md"; + if (!fs::is_regular_file(root_skill)) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} has no {}/SKILL.md (the standard layout's root)\n", + root.generic_string(), app); + return false; + } + if (!inside(root, root_skill)) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} points outside {}\n", + root_skill.generic_string(), root.generic_string()); + return false; + } + std::error_code ec; + std::vector dirs; + for (const auto& entry : fs::directory_iterator(root, ec)) { + if (ec) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: cannot read {}: {}\n", root.generic_string(), ec.message()); + return false; + } + if (entry.is_directory()) dirs.push_back(entry.path()); + } + std::ranges::sort(dirs); + for (const auto& dir_path : dirs) { + const std::string directory = dir_path.filename().generic_string(); + const fs::path file = dir_path / "SKILL.md"; + if (!fs::is_regular_file(file)) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} has no SKILL.md\n", dir_path.generic_string()); + return false; + } + if (!inside(root, file)) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} points outside {}\n", + file.generic_string(), root.generic_string()); + return false; + } + auto text = read_text(file, error); + if (!text) { + std::cerr << "mcpplibs.mplugin.cmdline: " << error << '\n'; + return false; + } + const auto meta = read_frontmatter(*text); + if (!meta) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} has no frontmatter\n", file.generic_string()); + return false; + } + if (meta->name != directory) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} names '{}', directory is '{}'\n", + file.generic_string(), meta->name, directory); + return false; + } + if (meta->description.empty()) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} has no description\n", file.generic_string()); + return false; + } + if (opt.max_lines != 0 && line_count(*text) > opt.max_lines) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} is {} lines (limit {})\n", + file.generic_string(), line_count(*text), opt.max_lines); + return false; + } + if (body(*text).empty()) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} has no instructions\n", file.generic_string()); + return false; + } + auto key = key_for(opt, app, directory, error); + if (key.empty()) { + std::cerr << "mcpplibs.mplugin.cmdline: " << error << '\n'; + return false; + } + if (!name_ok(key) || key.find("..") != std::string::npos) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: '{}' is not a valid skill key\n", key); + return false; + } + skills.push_back({std::move(key), directory, std::move(*text), file}); + } + if (skills.empty()) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} holds no skill\n", root.generic_string()); + return false; + } + if (const auto rel = fs::relative(root, manifest, ec); !ec) + mcpp::rerun_if_changed_glob((rel.generic_string() + "/*/SKILL.md").c_str()); + else + mcpp::rerun_if_changed_glob("docs/*-skills/*/SKILL.md"); + } else if (opt.fallback_agents) { + const fs::path agents = manifest / "AGENTS.md"; + if (!fs::is_regular_file(agents)) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: no {} and no {}\n", + root.generic_string(), agents.generic_string()); + return false; + } + auto text = read_text(agents, error); + if (!text) { + std::cerr << "mcpplibs.mplugin.cmdline: " << error << '\n'; + return false; + } + if (body(*text).empty()) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} is empty\n", agents.generic_string()); + return false; + } + skills.push_back({"root" + opt.key_suffix, "", std::move(*text), agents}); + const std::string warning = std::format( + "mcpplibs.mplugin.cmdline: {} not found; embedding {} as the root skill only", + root.generic_string(), agents.generic_string()); + std::cerr << warning << '\n'; + mcpp::warning(warning.c_str()); + mcpp::rerun_if_changed(agents.generic_string().c_str()); + } else { + std::cerr << std::format("mcpplibs.mplugin.cmdline: {} is not a directory\n", root.generic_string()); + return false; + } + + std::ranges::sort(skills, {}, &skill::key); + for (std::size_t i = 1; i < skills.size(); ++i) + if (skills[i].key == skills[i - 1].key) { + std::cerr << std::format("mcpplibs.mplugin.cmdline: duplicate skill key '{}'\n", skills[i].key); + return false; + } + + const fs::path out = opt.out_dir.empty() + ? fs::path(mcpp::out_dir()) / "include" / "mcpp.mplugin.cmdline" + : fs::path(opt.out_dir); + const fs::path header = out / (opt.identifier + ".h"); + if (!write_if_different(header, header_text(opt, app, skills), error)) { + std::cerr << "mcpplibs.mplugin.cmdline: " << error << '\n'; + return false; + } + for (const auto& skill : skills) mcpp::rerun_if_changed(skill.input.generic_string().c_str()); + if (opt.out_dir.empty()) mcpp::include_dir(out.generic_string().c_str()); + return true; +} + +/// `embed(options{})`: the standard layout, the app from the manifest. +inline bool embed_default() { return embed(options{}); } + +} // namespace mcpplibs::mplugin::cmdline diff --git a/src/agent_skills.cppm b/src/agent_skills.cppm new file mode 100644 index 0000000..9831b4b --- /dev/null +++ b/src/agent_skills.cppm @@ -0,0 +1,164 @@ +// The Agent Skills convention of `--agent-skill-doc`, as an optional module: +// a command answers its skill's markdown before any action (and therefore +// before an account, a config or a network), and the root's answer ends with +// an index. The module knows the flag and the frontmatter; the application +// provides the sheets (built into the binary) and, through `default_options`, +// the order the root and `self` list their commands in. +// +// This file is compiled only when the package's `agent-skills` feature is on; +// a CLI that does not call `install`/`install_default` has no such flag. +export module mcpplibs.cmdline.agent_skills; + +import std; +import mcpplibs.cmdline; + +export namespace mcpplibs::cmdline::agent_skills { + +/// The flag and the two lookups. `find` returns a skill's BODY (frontmatter +/// already removed); `index` appends what the body's answer ends with, and an +/// empty string appends nothing. Neither reads a file or the network. +struct options { + std::string flag = "agent-skill-doc"; + std::string help = "print the command's skill for agents"; + std::function(std::string_view)> find; + std::function index; +}; + +/// The order the two built-in indexes list their commands in. A simple CLI +/// passes neither: the root lists every key without a dot, and `self` has no +/// generated index (its sheet carries its own). +struct default_options { + std::vector root_commands; + std::vector self_commands; +}; + +namespace detail { + +/// The instructions: what follows the frontmatter; the whole text when it has +/// none. One blank line after the closing `---` belongs to the format, not to +/// the answer. +inline std::string_view body(std::string_view skill) { + if (!skill.starts_with("---\n")) return skill; + const auto end = skill.find("\n---\n", 4); + if (end == std::string_view::npos) return skill; + const auto rest = skill.substr(end + 5); + const auto first = rest.find_first_not_of('\n'); + return first == std::string_view::npos ? std::string_view{} : rest.substr(first); +} + +/// One line of the frontmatter (`name: gitany-pr`), trimmed; empty when the +/// sheet has no such field. The index reads these two fields and no more. +inline std::string_view frontmatter_field(std::string_view skill, std::string_view key) { + if (!skill.starts_with("---\n")) return {}; + const auto end = skill.find("\n---\n", 4); + if (end == std::string_view::npos) return {}; + const auto block = skill.substr(4, end - 4 + 1); + for (std::size_t i = 0; i < block.size();) { + const auto eol = block.find('\n', i); + const auto line = block.substr(i, eol == std::string_view::npos ? std::string_view::npos : eol - i); + i = eol == std::string_view::npos ? block.size() : eol + 1; + if (!line.starts_with(key) || line.size() <= key.size() || line[key.size()] != ':') continue; + const auto value = line.substr(key.size() + 1); + const auto first = value.find_first_not_of(' '); + return first == std::string_view::npos ? std::string_view{} : value.substr(first); + } + return {}; +} + +} // namespace detail + +/// Register the flag on `app`; `find` decides what each path answers. +inline void install(App& app, options o = {}) { + auto find = std::move(o.find); + auto index = std::move(o.index); + app.answer_flag(o.flag, o.help, + [find = std::move(find), index = std::move(index), name = std::string(app.name())]( + std::string_view path, const ParsedArgs&) -> std::optional { + const std::string_view key = path.empty() ? std::string_view("root") : path; + const auto body = find ? find(key) : std::nullopt; + if (!body) { + std::println(std::cerr, "{}: no skill for '{}'", name, key); + return 2; + } + std::print("{}", *body); + if (index) { + const auto extra = index(key); + if (!extra.empty()) std::print("{}", extra); + } + return 0; + }); +} + +/// Register the flag and answer from a built-in `sheet[]` table (the shape the +/// `mcpplibs.mplugin.cmdline` build plugin writes): exact key first, then the +/// path shortened by one dot-segment at a time (`self.auth.add` -> `self.auth` +/// -> `auth`). The root's answer gets an index of `root_commands`; `self`'s +/// gets one of `self_commands` when that list is given. +template +void install_default(App& app, const Sheet (&sheets)[N], default_options o = {}) { + const auto lookup = [&sheets](std::string_view key) -> std::optional { + for (const auto& row : sheets) + if (std::string_view(row.key) == key) + return std::string_view(reinterpret_cast(row.data), row.size); + return std::nullopt; + }; + // A table's keys may name their file (`pr.md`); the path does not. + const auto lookup_key = [lookup](std::string_view key) -> std::optional { + if (auto skill = lookup(key)) return skill; + if (!key.ends_with(".md")) { + const std::string with_suffix = std::string(key) + ".md"; + if (auto skill = lookup(with_suffix)) return skill; + } + return std::nullopt; + }; + auto find = [lookup_key](std::string_view path) -> std::optional { + if (path.empty()) path = "root"; + if (auto skill = lookup_key(path)) return detail::body(*skill); + while (true) { + const auto dot = path.rfind('.'); + if (dot == std::string_view::npos) return std::nullopt; + path = path.substr(0, dot); + if (auto skill = lookup_key(path)) return detail::body(*skill); + } + }; + auto index = [&sheets, lookup_key, root_commands = std::move(o.root_commands), + self_commands = std::move(o.self_commands), name = std::string(app.name())]( + std::string_view path) -> std::string { + if (path.empty()) path = "root"; + const bool root = path == "root"; + if (!root && path != "self") return {}; + std::vector commands; + if (root) { + if (!root_commands.empty()) { + for (const auto& command : root_commands) commands.push_back(command); + } else { + for (const auto& row : sheets) { + const std::string_view key(row.key); + if (key != "root" && key.find('.') == std::string_view::npos) commands.push_back(key); + } + } + } else { + for (const auto& command : self_commands) commands.push_back(command); + } + std::string text; + const std::string prefix = root ? name + " " : name + " self "; + for (const std::string_view command : commands) { + const auto skill = lookup_key(command); + if (!skill) continue; + const auto skill_name = detail::frontmatter_field(*skill, "name"); + const auto description = detail::frontmatter_field(*skill, "description"); + if (skill_name.empty()) continue; + text += "| `" + prefix + std::string(command) + " --agent-skill-doc` | " + + std::string(skill_name) + " | " + std::string(description) + " |\n"; + } + if (text.empty()) return {}; + return "\n## " + std::string(root ? "The skills in this binary" : "The skills under `" + name + " self`") + + "\n\n| command | skill | use it when |\n|---|---|---|\n" + text; + }; + install(app, options{.flag = "agent-skill-doc", + .help = "print the command's skill for agents", + .find = std::move(find), + .index = std::move(index)}); +} + +} // namespace mcpplibs::cmdline::agent_skills diff --git a/src/cmdline.cppm b/src/cmdline.cppm index 9bcf243..377ecf5 100644 --- a/src/cmdline.cppm +++ b/src/cmdline.cppm @@ -48,6 +48,12 @@ export enum class HelpOrder { declared, alphabetical }; export struct HelpOptions { HelpOrder order = HelpOrder::declared; std::string ungrouped; + /// A group is a TOP-LEVEL section of its own (`SUBCOMMANDS:`, + /// `SELF MANAGEMENT:`), with its commands one level below it, rather than + /// a second-level heading under one `SUBCOMMANDS:` list. Commands without + /// 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; }; export using detail::Arg; export using detail::Option; @@ -56,6 +62,13 @@ export using detail::ParseError; export using detail::ParseResult; export using detail::ParsedArgs; +/// What answers a flag after the parse and before any action: the dotted +/// command path (`self.auth`, `pr.create`), the parse the words produced, and +/// the status to exit with when the flag is answered. `nullopt` leaves the +/// flag to the next answerer (or to the action): one flag can have several +/// readers, and the first that answers wins. +export using FlagAnswer = std::function(std::string_view, const ParsedArgs&)>; + export class App { template friend class AppItemBuilder; friend class SubcommandBuilder; @@ -69,7 +82,7 @@ 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_) {} + epilogue_(other.epilogue_), answerers_(other.answerers_) {} App& operator=(const App& other) { if (this == &other) return *this; name_ = other.name_; @@ -85,9 +98,13 @@ public: group_ = other.group_; help_options_ = other.help_options_; epilogue_ = other.epilogue_; + answerers_ = other.answerers_; return *this; } + /// The program name this tree was declared with. + [[nodiscard]] std::string_view name() const { return name_; } + /// The command is not listed: not in help, not among completions. It /// parses and runs as any other (an internal command, a deprecated /// spelling). @@ -167,6 +184,32 @@ public: return *this; } + /// A flag answered after the parse and before the action (a manual page, + /// a schema, an agent skill: things an action must not need an account or + /// a network for). The flag is global — it parses at any depth — and + /// listed with the options, where `help` says what it prints. The answerer + /// sees the dotted path; `nullopt` passes the flag on. + [[nodiscard]] App& answer_flag(std::string_view name, std::string_view help, FlagAnswer answer) { + Option opt(name); + opt.help_ = help; + opt.global_ = true; + options_.push_back(std::move(opt)); + answerers_.push_back({std::string(name), std::move(answer)}); + return *this; + } + + /// Answers the registered flags set in `parsed`, in registration order. + /// Call it after `parse` and before building what an action needs; the + /// status is the one the first answerer returned. `run(parsed)` does not + /// answer — it runs the action — so a two-phase caller answers once. + [[nodiscard]] std::optional answer_flags(const ParsedArgs& parsed) const { + const std::string path = parsed.command_path(); + for (const auto& entry : answerers_) + if (parsed.is_flag_set(entry.name)) + if (auto status = entry.answer(path, parsed)) return status; + return std::nullopt; + } + [[nodiscard]] ParseResult parse(int argc, char* argv[]) const { std::vector tokens; tokens.reserve(argc > 1 ? argc - 1 : 0); @@ -249,17 +292,36 @@ public: && (program_name.empty() || program_name == name_); const auto commands = listed(*this, listsCompletion); if (!commands.empty()) { - std::println("\nSUBCOMMANDS:"); - 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; + const bool any_group = std::ranges::any_of(commands, [](const Listed& c) { return !c.group.empty(); }); + if (!help_options_.groups_as_sections || !any_group) { + std::println("\nSUBCOMMANDS:"); + std::string_view heading; + 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, c.description); + } + } else { + // One top-level section per group: the heading the command's + // `group` names, nothing between it and the command's level. + std::string_view heading; + for (const auto& c : commands) { + const std::string_view under = c.group.empty() + ? (help_options_.ungrouped.empty() ? std::string_view("SUBCOMMANDS") : std::string_view(help_options_.ungrouped)) + : c.group; + if (under != heading) { + std::println("\n{}:", under); + heading = under; + } + std::string padded(c.name); + while (padded.size() < 12) padded += ' '; + std::println(" {} {}", padded, c.description); } - std::string padded(c.name); - while (padded.size() < 12) padded += ' '; - std::println(" {} {}", padded, c.description); } } if (!epilogue_.empty()) std::print("\n{}{}", epilogue_, epilogue_.ends_with('\n') ? "" : "\n"); @@ -304,6 +366,7 @@ private: std::println(std::cerr, "{}: see '{} --help'", name_, name_); return 2; } + if (auto status = answer_flags(*result)) return *status; return run(*result); } @@ -536,6 +599,11 @@ private: std::vector