diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d069ce..7d12533 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 0.3.1 - 2026-11-15 + +### Fixed + +- `--json` 且无命令时只向 stderr 输出 `{ error }`,不再向 stdout 写 usage,与“`--json` 错误只写 stderr”的契约一致。 + ## 0.3.0 - 2026-11-15 ### Added diff --git a/package.json b/package.json index aceab1f..906d767 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ultime/cli", - "version": "0.3.0", + "version": "0.3.1", "description": "Ultime · cli:通用命令行设施(参数 / 命令注册 / 上下文 / 退出码),零领域依赖", "keywords": [ "argument-parser", diff --git a/src/run.ts b/src/run.ts index 15a6a75..4be1c97 100644 --- a/src/run.ts +++ b/src/run.ts @@ -152,7 +152,18 @@ export async function runCli(spec: CliSpec, argv: string[], ctx: CliContext = pr return EXIT_OK } if (!args.command) { - ctx.out(spec.usage) + if (json) { + reportError( + ctx, + new CliError('缺少命令', { + code: 'USAGE', + hint: `可用命令:${Object.keys(spec.commands).join(' / ')}`, + }), + true, + ) + } else { + ctx.out(spec.usage) + } return EXIT_USAGE } diff --git a/tests/infra.test.ts b/tests/infra.test.ts index 837b593..cc7c1eb 100644 --- a/tests/infra.test.ts +++ b/tests/infra.test.ts @@ -333,6 +333,16 @@ describe('cli · 运行时', () => { expect(out).toEqual(['demo ']) }) + it('--json 下无命令只写 stderr', async () => { + const { ctx, err, out } = collector() + expect(await runCli(spec, ['--json'], ctx)).toBe(2) + expect(out).toEqual([]) + const payload = JSON.parse(err.join('\n')) as { error: { code: string; message: string; hint?: string } } + expect(payload.error.code).toBe('USAGE') + expect(payload.error.message).toBe('缺少命令') + expect(payload.error.hint).toContain('ping') + }) + it('未知命令返回 2,并给最近候选', async () => { const { ctx, err, out } = collector() expect(await runCli(spec, ['statsu'], ctx)).toBe(2)