Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

- **Shell 补全** — `app.completion()` 一次调用开启;程序以自己的命令树回答(`__complete`),bash、zsh、fish、PowerShell 的适配脚本只有几行,不含命令树
- **数值选项** — `value_type<T>()` 声明选项取 `T` 类型的数字,解析时用 `std::from_chars` 校验,不合法就是解析错误;`value_as<T>(name)` 读回
- **分组的 help** — 子命令的 `.group(s)` 给出标题,`.help_options({ .order = alphabetical, .ungrouped = "…" })` 定次序,`.help_epilogue(s)` 在列表后写例子;help、补全候选与“缺子命令”的报错用同一份列表

## 快速开始

Expand Down
37 changes: 34 additions & 3 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
| `Argv` | `std::vector<std::string>` 的别名,用于 `parse_from` |
| `Shell` | 目标 shell 枚举:`bash` / `fish` / `zsh` / `powershell` |
| `Command` | 命令树快照,补全引擎读取它 |
| `CompletionOptions` | 补全的开启方式:可见命令名、隐藏入口、它在 help 里的分组 |
| `HelpOrder` · `HelpOptions` | help 列出子命令的次序与标题(`App::help_options`,见“帮助的列表”) |

解析返回 `ParseResult`,即 `std::expected<ParsedArgs, ParseError>`。`-h`/`--help`、`--version` 时,`ParseError::kind` 分别为 `help` / `version`(补全见“Shell 补全”,为 `completion`),不携带 `message`,通过 `is_error()` 可区分真实错误。

Expand All @@ -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
```

---

Expand All @@ -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)`

---

Expand Down Expand Up @@ -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 起输出适配脚本,而不是
写出整棵命令树的脚本。
Expand Down
2 changes: 1 addition & 1 deletion mcpp.toml
Original file line number Diff line number Diff line change
@@ -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"]
Expand Down
129 changes: 111 additions & 18 deletions src/cmdline.cppm
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,37 @@ 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<std::string>;

/// 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;
Expand All @@ -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_;
Expand All @@ -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;
}

Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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> listed(const App& app, bool with_completion) {
std::vector<Listed> 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<std::string_view> 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<std::size_t>(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 &sub;
Expand Down Expand Up @@ -452,6 +538,9 @@ private:
std::function<int(const ParsedArgs&)> action_;
bool hidden_ = false;
std::optional<CompletionOptions> completion_;
std::string group_;
HelpOptions help_options_;
std::string epilogue_;
};

// CRTP base: shared transition methods and parent/commit management for OptBuilder & ArgBuilder.
Expand Down Expand Up @@ -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; }
Expand Down Expand Up @@ -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";
Expand Down
Loading
Loading