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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# AGENTS.md — @ultime/cli

> 给在本仓库工作的 AI 与协作者:入口、可写 / 只读、红线与验收。
> 适用版本:0.3.x
> 适用版本:0.4.x

## 先读

Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 0.4.0 - 2026-11-15

### Added

- `CliSpec.defaultCommand`:无命令时执行默认命令;设置后未注册的首个 token 作为默认命令的 positional,显式命令优先;有默认命令时 `--` 之后全部按 positional 处理,不改变 help / version。

## 0.3.1 - 2026-11-15

### Fixed
Expand Down
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,24 @@ commands: {
- 未声明:传了 schema 时按布尔解析,再由 `runCli` 以 `USAGE` 拒绝;不传 schema 时保持旧的自由解析;
- 同一 flag 在所有命令中的类型必须一致;命令要么全部声明 `flags`,要么全部省略。

## 默认命令

命令面有默认动作时(例如检查工具的 `run`),在 `CliSpec` 设置 `defaultCommand`:

```ts
const spec = {
name: 'my-cli',
version: '0.1.0',
usage: 'my-cli [command]',
defaultCommand: 'run',
commands: {
run: { flags: {}, run: (args, ctx) => 0 },
},
}
```

无命令时执行默认命令;设置默认命令后,未注册的首个 token 也作为它的 positional(显式注册的命令优先),不再报未知命令。有默认命令时 `--` 之后全部作为 positional。`--help` / `--version` 仍走全局短路,不会误执行默认命令。

## 错误与退出码

命令用 `CliError` 抛机器可读错误;普通异常退化成 `code: 'ERROR'`:
Expand Down Expand Up @@ -121,8 +139,9 @@ tests/ 参数、运行时、声明校验与包内容边界

## 版本与兼容

- 当前 `0.3.x`;0.x 阶段 API 仍可能调整。
- 当前 `0.4.x`;0.x 阶段 API 仍可能调整。
- 退出码语义:0 成功 / 1 命令执行失败 / 2 用法或配置错误;这是 0.2 起的新约定,升级时按本节目迁移。
- 0.4 新增 `CliSpec.defaultCommand`;无命令时执行默认命令,`--` 的解析随之调整。
- 0.3 的破坏性变更:`runCli` 改为异步;声明 `flags` 后未知参数与缺值会被拒绝。迁移方式:入口改成 `process.exitCode = await runCli(...)`,并给命令补 `flags`;不补 `flags` 的命令仍按旧规则解析。
- 破坏性变更写进 [CHANGELOG](./CHANGELOG.md),并在本节目说明迁移方式。
- 发布顺序:本包是基础设施,先于依赖它的包。
Expand Down
9 changes: 5 additions & 4 deletions SKILLS.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# @ultime/cli · 可调用能力

> 定位:AI 可调用的通用命令设施。领域命令不在这里。
> 适用版本:0.3.x
> 同步基线:0.3.x(手写;API 变化时同批更新)
> 适用版本:0.4.x
> 同步基线:0.4.x(手写;API 变化时同批更新)

---

Expand Down Expand Up @@ -42,6 +42,7 @@ import type {
name: string
version: string
usage: string
defaultCommand?: string
commands: Record<string, {
help?: string | ((args: ParsedArgs) => string)
flags?: Record<string, 'boolean' | 'string'>
Expand All @@ -53,8 +54,8 @@ import type {

## 错误语义

- 未知命令:`err` 写错误与候选,`out` 写 usage,返回 2;
- 无命令:`out` 写 usage,返回 2;
- 未知命令:未设置 `defaultCommand` 时 `err` 写错误与候选、`out` 写 usage,返回 2;设置后未注册 token 转入默认命令的 positional;
- 无命令:设置 `defaultCommand` 时执行它;否则 `out` 写 usage,返回 2;
- 未知参数 / 布尔参数带值 / 带值参数缺值:`CliError`(`USAGE`),返回 2;
- 普通异常:`err` 写 message,`code: 'ERROR'`,返回 1;
- `CliError`:带 `code` / `path` / `hint`,返回 `exitCode`(默认 2);
Expand Down
2 changes: 1 addition & 1 deletion llms.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# @ultime/cli · AI 索引

适用版本:0.3.x
适用版本:0.4.x

## 去哪找

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ultime/cli",
"version": "0.3.1",
"version": "0.4.0",
"description": "Ultime · cli:通用命令行设施(参数 / 命令注册 / 上下文 / 退出码),零领域依赖",
"keywords": [
"argument-parser",
Expand Down
2 changes: 1 addition & 1 deletion rules/01-architecture.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# 01 · 架构与依赖

> 定位:CLI 设施的职责、依赖方向与目录分工。
> 适用版本:0.3.x
> 适用版本:0.4.x
> 关系:规则索引见 [`README`](./README.md);运行协议见 [`02-runner`](./02-runner.md)。

---
Expand Down
6 changes: 5 additions & 1 deletion rules/02-runner.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# 02 · 参数、命令与退出码

> 定位:`runCli` 的稳定协议。
> 适用版本:0.3.x
> 适用版本:0.4.x
> 关系:架构见 [`01-architecture`](./01-architecture.md)。

---
Expand Down Expand Up @@ -34,6 +34,10 @@ deploy: {
- 未声明的 flag 在传 schema 时按布尔解析,由 `runCli` 拒绝;
- 同一 flag 的类型必须跨命令一致;命令要么全部声明,要么全部省略。

## 默认命令

`CliSpec.defaultCommand` 指定无命令时执行的命令;`--help` / `--version` 仍走全局短路,不执行默认命令。设置默认命令后,未注册的首个 token 作为默认命令的 positional(显式注册的命令优先);`--` 之后全部按 positional 处理,不再把首个 token 当命令。

## 命令注册

```ts
Expand Down
3 changes: 2 additions & 1 deletion rules/03-testing.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# 03 · 测试与验收

> 定位:改 CLI 设施时跑什么、什么算通过。
> 适用版本:0.3.x
> 适用版本:0.4.x
> 关系:协议见 [`02-runner`](./02-runner.md);发布检查见 [`04-release`](./04-release.md)。

---
Expand All @@ -19,6 +19,7 @@ pnpm test

- 参数:命令、布尔 flag、`key=value`、带值 flag;
- schema:声明布尔 / 字符串、未知 flag、`--` 终止符与空字符串;
- 默认命令:无命令执行默认命令、未注册 token 归 positional、显式命令优先、`--` 之后全部 positional、help / version 不误执行;
- 校验:未知参数、布尔显式值、字符串缺值、混合声明与类型冲突;
- 运行时:版本 / 帮助不执行命令;异步命令与异常;`mapError`;未知命令与异常都转退出码;已注册命令能分发;
- 辅助出口:`flagBool` / `flagValue` / `reportError` / `exitCodeOf` 与退出码常量。
Expand Down
2 changes: 1 addition & 1 deletion rules/04-release.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# 04 · 版本与发布

> 定位:CLI 设施的编译 ESM 形态、发布顺序与检查。
> 适用版本:0.3.x
> 适用版本:0.4.x
> 关系:测试见 [`03-testing`](./03-testing.md)。

---
Expand Down
2 changes: 1 addition & 1 deletion rules/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# cli · 开发规则

> 定位:本包开发规范的索引。只写判断、边界与反例;API 事实以 README 为准。
> 适用版本:0.3.x
> 适用版本:0.4.x
> owner:维护者(repo owner)· 复核:2026-11-11 · 到期降级为参考
> 关系:入口见 [`AGENTS.md`](../AGENTS.md);怎么用见 [`README.md`](../README.md)。

Expand Down
3 changes: 3 additions & 0 deletions src/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export type FlagSpec = Record<string, FlagType>

export interface ParseOptions {
flags?: FlagSpec
/** 有默认命令时,`--` 之后全部作为 positional,不再把首个 token 当命令。 */
defaultCommand?: string
}

/** 通用布尔 flag:只表达输出形态,不承载业务语义。 */
Expand All @@ -42,6 +44,7 @@ export function parseArgs(argv: string[], options: ParseOptions = {}): ParsedArg
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i]
if (token === '--') {
if (!command && options.defaultCommand) command = options.defaultCommand
for (const rest of argv.slice(i + 1)) {
if (!command) command = rest
else positional.push(rest)
Expand Down
11 changes: 10 additions & 1 deletion src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export interface CliSpec {
name: string
version: string
usage: string
/** 无命令时执行的默认命令;只影响分发,不改变 help / version。 */
defaultCommand?: string
commands: Record<string, CommandSpec>
/** 把领域错误转成 CliError;返回 undefined 表示保持原样 */
mapError?: (error: unknown) => CliError | undefined
Expand Down Expand Up @@ -134,7 +136,7 @@ export function reportError(ctx: CliContext, error: unknown, json: boolean): voi
}

export async function runCli(spec: CliSpec, argv: string[], ctx: CliContext = processContext()): Promise<number> {
const args = parseArgs(argv, { flags: collectFlags(spec.commands) })
const args = parseArgs(argv, { flags: collectFlags(spec.commands), defaultCommand: spec.defaultCommand })
const json = args.flags.json === true

if (args.flags.version) {
Expand All @@ -151,6 +153,13 @@ export async function runCli(spec: CliSpec, argv: string[], ctx: CliContext = pr
ctx.out(typeof help === 'function' ? help(args) : (help ?? `${spec.name} ${args.command} [options]`))
return EXIT_OK
}
if (args.command && spec.defaultCommand && !commandOf(spec.commands, args.command)) {
args.positional.unshift(args.command)
args.command = spec.defaultCommand
}
if (!args.command && spec.defaultCommand) {
args.command = spec.defaultCommand
}
if (!args.command) {
if (json) {
reportError(
Expand Down
69 changes: 69 additions & 0 deletions tests/infra.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,29 @@ const strict: CliSpec = {
error instanceof DomainError ? new CliError(error.message, { code: error.code, path: error.path }) : undefined,
}

const defaultSpec: CliSpec = {
name: 'demo',
version: '1.2.3',
usage: 'demo [command]',
defaultCommand: 'run',
commands: {
run: {
flags: { quiet: 'boolean' },
run: (args, ctx) => {
ctx.out(`run:${args.positional.join(',')}:${flagBool(args, 'json')}`)
return EXIT_OK
},
},
rules: {
flags: {},
run: (_args, ctx) => {
ctx.out('rules')
return EXIT_OK
},
},
},
}

describe('cli · 参数', () => {
it('解析命令、布尔 flag、带值 flag 与 key=value', () => {
const args = parseArgs(['build', '--check', '--config=foo.json', '--cwd', 'dir'])
Expand Down Expand Up @@ -188,6 +211,52 @@ describe('cli · 参数 schema', () => {
})
})

describe('cli · 默认命令', () => {
it('parseArgs 在 -- 之后把默认命令与 positional 分开', () => {
expect(parseArgs(['--', '-file'], { defaultCommand: 'run', flags: { quiet: 'boolean' } })).toEqual({
command: 'run',
flags: {},
positional: ['-file'],
})
})

it('无命令执行默认命令', async () => {
const { ctx, out } = collector()
expect(await runCli(defaultSpec, [], ctx)).toBe(0)
expect(out).toEqual(['run::false'])
})

it('--help 无显式命令仍显示全局 usage', async () => {
const { ctx, out } = collector()
expect(await runCli(defaultSpec, ['--help'], ctx)).toBe(0)
expect(out).toEqual(['demo [command]'])
})

it('-- 之后全部作为默认命令的位置参数', async () => {
const { ctx, out } = collector()
expect(await runCli(defaultSpec, ['--', '-file', 'x'], ctx)).toBe(0)
expect(out).toEqual(['run:-file,x:false'])
})

it('显式命令优先于默认命令', async () => {
const { ctx, out } = collector()
expect(await runCli(defaultSpec, ['rules'], ctx)).toBe(0)
expect(out).toEqual(['rules'])
})

it('未注册的首个 token 作为默认命令的位置参数', async () => {
const { ctx, out } = collector()
expect(await runCli(defaultSpec, ['file', 'dir'], ctx)).toBe(0)
expect(out).toEqual(['run:file,dir:false'])
})

it('默认命令也支持 --json', async () => {
const { ctx, out } = collector()
expect(await runCli(defaultSpec, ['--json'], ctx)).toBe(0)
expect(out).toEqual(['run::true'])
})
})

describe('cli · 声明与校验', () => {
it('布尔 flag 写在 positional 前也能正确分发', async () => {
const { ctx, out } = collector()
Expand Down
Loading