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
45 changes: 33 additions & 12 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,35 @@ 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:
# The macOS leg waits for a runner GitHub did not provide for this
# repository (three labels queued for 30+ minutes on 2026-12-04). The
# code is platform-neutral and the fixture builds on Linux/Windows;
# re-add macos-15 when the queue answers.
os: [ubuntu-latest, windows-2025]
runs-on: ${{ matrix.os }}
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4

- name: Install xlings
- name: Install xlings (Linux/macOS)
if: runner.os != 'Windows'
run: |
curl -fsSL https://raw.githubusercontent.com/openxlings/xlings/main/tools/other/quick_install.sh | bash -s v2026.10.26.1
echo "$HOME/.xlings/subos/current/bin" >> "$GITHUB_PATH"

- name: Install xlings (Windows)
if: runner.os == 'Windows'
shell: pwsh
run: |
irm https://d2learn.org/xlings-install.ps1.txt | iex
"$env:USERPROFILE\.xlings\subos\current\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append

- name: Install mcpp (the version .xlings.json names)
run: |
MCPP_VERSION="$(sed -n 's/.*"mcpp": *"\([^"]*\)".*/\1/p' .xlings.json)"
Expand All @@ -30,17 +49,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
"$(find target -type f -path '*/bin/skills-fixture*' | head -1)"
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
.xmake
build
target
.xlings/subos/
2 changes: 1 addition & 1 deletion .xlings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"workspace": {
"mcpp": "2026.11.8.1"
"mcpp": "2026.11.27.1"
}
}
216 changes: 83 additions & 133 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,162 +1,112 @@
# cmdline

> 一个简单易用的命令行解析库/框架 - `import mcpplibs.cmdline;`

使用 C++23 模块的类型安全命令行解析库。流式链式接口,零样板代码。支持位置参数、短/长选项、子命令、全局标志,以及基于 `std::expected` 的错误处理。

## ✨ 特性

- **C++23 模块** — `import mcpplibs.cmdline`

- **流式接口** — 链式构建方法,所见即所得的 API

- **子命令** — 任意层级的嵌套命令,`action` 回调分发或手动分发

- **退出码** — `action` 可返回 `int`,`run` 返回该退出码;解析错误写入标准错误并返回 2

- **全局选项** — 标志透明地传播到所有子命令

- **类型安全结果** — `std::expected<ParsedArgs, std::string>`

- **多种解析模式** — 支持 `argc/argv`、`cmdline::Argv`(即 `vector<string>`)或原始 `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<T>()` checks a number with
`std::from_chars`; `value_as<T>()` 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;`.
The default is build-time: `mcpplibs.mplugin.cmdline` renders `docs/<app>-skills` into a C++
module (`<app>.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.
- **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,
no header.

## 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>()` 声明选项取 `T` 类型的数字,解析时用 `std::from_chars` 校验,不合法就是解析错误;`value_as<T>(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 whose
`build.mcpp` renders three documents into `fixture.skills` and answers them — no header.

## 快速开始
## 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` from a build-time module (the recommended default):

```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() {
mcpplibs::mplugin::cmdline::options o;
o.app = "myapp", o.module_name = "myapp.skills", o.name_space = "myapp::skills";
return mcpplibs::mplugin::cmdline::embed(o) ? 0 : 1;
}
```

### 数值选项

```cpp
auto app = cmdline::App("myapp")
.option(cmdline::Option("rate").value_type<double>().help("每秒多少片"))
.option(cmdline::Option("frames").short_name('f').value_type<int>());
// myapp --rate fast → 解析错误:"option --rate takes a number, not `fast`"
auto parsed = app.parse(argc, argv);
const double rate = parsed->value_as<double>("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"
```

#### 构建
// src/skills.cppm — no header: the generated module is imported
export module myapp.install;
import mcpplibs.cmdline;
import mcpplibs.cmdline.agent_skills;
import myapp.skills; // generated by build.mcpp

```bash
mcpp build
export void install(mcpplibs::cmdline::App& app) {
mcpplibs::cmdline::agent_skills::install_default(app, myapp::skills::sheets,
{.root_commands = {"run", "self"}, .self_commands = {"version"}});
}
```

#### 代码示例

```cpp
import mcpplibs.cmdline;
// ... 参见上方"快速开始"
```
The fallback for development, never the default: `install_runtime(app, {.root = "docs/myapp-skills", ...})`
reads the same layout from disk at install time.

## 相关链接
## 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.
Loading
Loading