diff --git a/AGENTS.md b/AGENTS.md index 04b17c0..a7cb439 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md — @ultime/cli > 给在本仓库工作的 AI 与协作者:入口、可写 / 只读、红线与验收。 -> 适用版本:0.4.x +> 适用版本:0.5.x ## 先读 @@ -14,7 +14,7 @@ | 路径 | 条件 | |---|---| -| `src/args.ts` / `src/context.ts` / `src/run.ts` | 通用设施;保持零依赖 | +| `src/args.ts` / `src/context.ts` / `src/run.ts` / `src/style.ts` | 通用设施;保持零依赖 | | `src/index.ts` | 公共出口;新增 API 同步 README / `SKILLS.md` | | `tests/**` | 与 API 改动同批 | | `rules/` / `llms.txt` / `SKILLS.md` | 随版本同批更新 | @@ -26,10 +26,10 @@ - **零领域依赖**:不 import 任何领域包;不内置具体命令。 - **不发 bin、不做命令发现**:每个产品包自带入口;本包不聚合、不扫描其他包的 bin。 - **不做 IO 策略**:读盘写盘与配置路径由命令自己决定。 -- **不引第三方解析库**:`parseArgs` 保持零依赖。 +- **不引第三方解析 / 着色库**:`parseArgs` 与 ANSI 着色都保持零依赖;颜色由 `CliContext.color` 控制。 - **runCli 异步**:命令返回 `number | Promise`;入口必须 `await` 后再赋给 `process.exitCode`。 - **开发方式**:测试先行;阶段完成先 review 代码与文档;文档简洁、机制优先。 -- **API 变化同步**:`runCli` / `ParsedArgs` / `FlagSpec` / `CliContext` 变化时同步 README、`SKILLS.md` 与测试。 +- **API 变化同步**:`runCli` / `ParsedArgs` / `FlagSpec` / `CliContext` 变化,或新增公共出口时,同步 README、`SKILLS.md` 与测试。 ## 验证 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a5d0b9..0745f67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 0.5.0 - 2026-11-22 + +### Added + +- `CliContext.color`:可选颜色开关;`processContext()` 按 stderr TTY、`FORCE_COLOR`、`NO_COLOR` / `NODE_DISABLE_COLORS` 与 `TERM` 计算。未设置时视为关闭,测试与管道输出无色。 +- 颜色渲染:错误标红、错误码弱化;自研 ANSI,不新增依赖。 + +### Changed + +- 文本错误首行显示稳定 code:`✗ [USAGE] 缺少 --config`;普通异常的 `ERROR` 不显示。`--json` 结构不变。 +- `details` 明确只进 JSON,文本不展开。 + ## 0.4.0 - 2026-11-15 ### Added diff --git a/README.md b/README.md index 5022223..93e5195 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ process.exitCode = await runCli(spec, process.argv.slice(2), processContext()) | 入口 | 提供 | |---|---| -| `@ultime/cli` | `parseArgs` / `flagBool` / `flagValue` / `runCli` / `reportError` / `processContext` / `CliError` / `toErrorShape` / `exitCodeOf` / `EXIT_OK` / `EXIT_FAIL` / `EXIT_USAGE` / `CliContext` / `CliSpec` / `CommandSpec` / `FlagType` / `FlagSpec` / `ParseOptions` / `ParsedArgs` / `CliErrorOptions` / `CliErrorShape` | +| `@ultime/cli` | `parseArgs` / `flagBool` / `flagValue` / `runCli` / `reportError` / `processContext` / `CliError` / `toErrorShape` / `exitCodeOf` / `style` / `supportsColor` / `EXIT_OK` / `EXIT_FAIL` / `EXIT_USAGE` / `CliContext` / `CliSpec` / `CommandSpec` / `FlagType` / `FlagSpec` / `ParseOptions` / `ParsedArgs` / `CliErrorOptions` / `CliErrorShape` / `StyleFormat` | `parseArgs` 只认 `command`、`--flag`、`--key value` / `--key=value`;`-h/--help`、`-v/--version` 与 `--json` 是保留 flag。`--` 之后全部按 positional 处理,`--key ""` 保留空字符串。 @@ -115,13 +115,15 @@ throw new CliError('缺少 --config', { ``` - 人类文案与 JSON 同源,由 `toErrorShape` 统一转换。 +- 文本错误首行显示稳定错误码:`✗ [USAGE] 缺少 --config`;普通异常的 `ERROR` 不显示,避免噪音。`details` 只进 JSON,不在文本里猜结构。 +- 颜色由 `CliContext.color` 控制;`processContext()` 按 stderr TTY、`FORCE_COLOR`、`NO_COLOR` / `NODE_DISABLE_COLORS` 与 `TERM` 计算,测试和管道输出默认无色。 AI 入口:[`llms.txt`](./llms.txt)(路由)与 [`SKILLS.md`](./SKILLS.md)(能力表)随包发布。 ## 边界 - **零领域依赖**:不 import 任何领域包,也不认识具体业务对象。 -- **不引第三方解析 / 着色库**:解析用零依赖实现,着色直接用 ANSI。Node 内置 `util.parseArgs` 表达不了自由 `--key value` 与命令级 flag schema,暂不切换。 +- **不引第三方解析 / 着色库**:解析用零依赖实现,着色用自研 ANSI;颜色由 `CliContext.color` 决定,不在输出时二次探测终端。Node 内置 `util.parseArgs` 表达不了自由 `--key value` 与命令级 flag schema,暂不切换。 - **不内置命令、不发 bin**:具体命令由调用方包注册,各自发布自己的 bin;本包不做命令发现与聚合。 - **不做 IO 策略**:读盘写盘、配置路径由命令自己决定;本包只提供 `cwd` 与 `out/err`。 @@ -130,16 +132,18 @@ AI 入口:[`llms.txt`](./llms.txt)(路由)与 [`SKILLS.md`](./SKILLS.md) ```text src/ args.ts 参数解析(纯函数)、flag schema 与读取 - context.ts 命令上下文(cwd / out / err) + context.ts 命令上下文(cwd / out / err / color)与进程实现 error.ts 机器可读错误、退出码与统一转换 run.ts 命令注册、flags 校验、help、未知命令与退出码 + style.ts 颜色包装(自研 ANSI,三个语义色) index.ts 公共出口 tests/ 参数、运行时、声明校验与包内容边界 ``` ## 版本与兼容 -- 当前 `0.4.x`;0.x 阶段 API 仍可能调整。 +- 当前 `0.5.x`;0.x 阶段 API 仍可能调整。 +- 0.5 新增:文本错误显示 `[CODE]`,新增 `CliContext.color` 与 `style` / `supportsColor` 导出;`--json` 结构不变。 - 退出码语义:0 成功 / 1 命令执行失败 / 2 用法或配置错误;这是 0.2 起的新约定,升级时按本节目迁移。 - 0.4 新增 `CliSpec.defaultCommand`:无命令时执行默认命令;未注册的首个 token 转为它的 positional,显式命令优先;有默认命令时 `--` 之后全部按 positional 处理。 - 0.3 的破坏性变更:`runCli` 改为异步;声明 `flags` 后未知参数与缺值会被拒绝。迁移方式:入口改成 `process.exitCode = await runCli(...)`,并给命令补 `flags`;不补 `flags` 的命令仍按旧规则解析。 diff --git a/SKILLS.md b/SKILLS.md index 6cd223e..2656432 100644 --- a/SKILLS.md +++ b/SKILLS.md @@ -1,15 +1,15 @@ # @ultime/cli · 可调用能力 > 定位:AI 可调用的通用命令设施。领域命令不在这里。 -> 适用版本:0.4.x -> 同步基线:0.4.x(手写;API 变化时同批更新) +> 适用版本:0.5.x +> 同步基线:0.5.x(手写;API 变化时同批更新) --- ## 入口 ```ts -import { flagBool, flagValue, parseArgs, processContext, reportError, runCli, CliError } from '@ultime/cli' +import { flagBool, flagValue, parseArgs, processContext, reportError, runCli, style, supportsColor, CliError } from '@ultime/cli' import type { CliContext, CliSpec, @@ -20,6 +20,7 @@ import type { ParsedArgs, CliErrorOptions, CliErrorShape, + StyleFormat, } from '@ultime/cli' ``` @@ -31,7 +32,9 @@ import type { | `runCli(spec, argv, ctx?)` | `CliSpec` + 参数 | `Promise<退出码>`;版本 / 帮助 / 未知命令 / 校验 / 错误由它处理 | | `reportError(ctx, error, json)` | 上下文 + 任意异常 + 是否 JSON | 统一错误输出 | | `exitCodeOf(error)` | 任意异常 | `CliError.exitCode` 或 1 | -| `processContext()` | — | `{ cwd, out, err }` | +| `processContext()` | — | `{ cwd, out, err, color }` | +| `style(enabled, format, text)` | 是否着色 + `red` / `yellow` / `dim` + 文案 | 带色或原文 | +| `supportsColor(stream?, env?)` | 输出流 + 环境变量 | 是否启用颜色 | | `CliError(message, options)` | 文案 + `code` / `path` / `hint` / `details` / `exitCode` | 可被 `runCli` 统一输出的错误 | | `toErrorShape(error)` | 任意异常 | `{ code, message, path?, hint?, details? }` | @@ -57,8 +60,9 @@ import type { - 未知命令:未设置 `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); +- 普通异常:`err` 写 message,`code: 'ERROR'`,返回 1;文本不显示 `[ERROR]`; +- `CliError`:带 `code` / `path` / `hint`,返回 `exitCode`(默认 2);文本首行 `✗ [CODE] message`,`details` 只进 JSON; +- 颜色:只由 `ctx.color` 控制;`processContext()` 按 stderr TTY 与环境变量计算,其余上下文默认无色; - `--json`:错误以 `{ "error": { … } }` 只写 stderr; - 版本 / 帮助:返回 0,不执行命令。 diff --git a/llms.txt b/llms.txt index 83ffe0d..27e8816 100644 --- a/llms.txt +++ b/llms.txt @@ -1,6 +1,6 @@ # @ultime/cli · AI 索引 -适用版本:0.4.x +适用版本:0.5.x ## 去哪找 @@ -9,7 +9,7 @@ ## 机器入口 -- 公共出口:`@ultime/cli` 的 `parseArgs` / `flagBool` / `flagValue` / `runCli` / `reportError` / `processContext` / `CliError` / `toErrorShape` / `exitCodeOf` 与类型。 +- 公共出口:`@ultime/cli` 的 `parseArgs` / `flagBool` / `flagValue` / `runCli` / `reportError` / `processContext` / `style` / `supportsColor` / `CliError` / `toErrorShape` / `exitCodeOf` 与类型。 ## 边界 diff --git a/package.json b/package.json index d278071..8df7b46 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ultime/cli", - "version": "0.4.0", + "version": "0.5.0", "description": "Ultime · cli:通用命令行设施(参数 / 命令注册 / 上下文 / 退出码),零领域依赖", "keywords": [ "argument-parser", diff --git a/rules/01-architecture.md b/rules/01-architecture.md index 29b20d6..95bf64f 100644 --- a/rules/01-architecture.md +++ b/rules/01-architecture.md @@ -1,7 +1,7 @@ # 01 · 架构与依赖 > 定位:CLI 设施的职责、依赖方向与目录分工。 -> 适用版本:0.4.x +> 适用版本:0.5.x > 关系:规则索引见 [`README`](./README.md);运行协议见 [`02-runner`](./02-runner.md)。 --- @@ -12,7 +12,7 @@ |---|---| | 参数解析、help、版本、未知命令、退出码与错误模型 | 定义任何领域命令 | | 命令注册与分发 | 读配置、写产物、判断配置合法性 | -| 提供 `cwd` 与 `out/err` 上下文 | 决定日志格式、文件布局或 IO 策略 | +| 提供 `cwd`、`out/err` 与颜色开关 | 决定日志格式、文件布局或 IO 策略 | | 提供 `CliError` / `toErrorShape` 与 `--json` 错误输出 | 发布 bin、发现或聚合其他包的命令 | 依赖方向: @@ -29,9 +29,10 @@ | 路径 | 职责 | |---|---| | `src/args.ts` | `command` / `--flag` / `--key value` 解析、`FlagSpec` 与 flag 读取 | -| `src/context.ts` | `CliContext` 与进程实现 | +| `src/context.ts` | `CliContext`、颜色开关与进程实现 | | `src/error.ts` | `CliError` / `toErrorShape` / 退出码常量 | | `src/run.ts` | `runCli`:版本 / 帮助 / 未知命令 / flags 校验 / 错误转退出码 | +| `src/style.ts` | 颜色包装:只由 `ctx.color` 决定,自研 ANSI | | `src/index.ts` | 公共出口 | ## 反例 diff --git a/rules/02-runner.md b/rules/02-runner.md index 98399c6..f23ffbb 100644 --- a/rules/02-runner.md +++ b/rules/02-runner.md @@ -1,7 +1,7 @@ # 02 · 参数、命令与退出码 > 定位:`runCli` 的稳定协议。 -> 适用版本:0.4.x +> 适用版本:0.5.x > 关系:架构见 [`01-architecture`](./01-architecture.md)。 --- @@ -71,6 +71,13 @@ runCli({ 普通异常没有字段信息,统一成 `{ code: 'ERROR', message }`。`exitCodeOf` 把 `CliError` 的 `exitCode` 或普通异常的 1 统一取出来;`EXIT_OK` / `EXIT_FAIL` / `EXIT_USAGE` 是稳定常量。 +文本输出: + +- 首行 `✗ [CODE] message`;`ERROR` 视为没有 code,首行退回 `✗ message`; +- 有 `path` / `hint` 时依次追加 `位置:` / `提示:`; +- `details` 只进 JSON,文本不展开; +- 颜色只由 `ctx.color` 决定:`processContext()` 按 stderr TTY 与环境变量计算,其余上下文默认无色;文本去色后信息必须完整。 + ## 退出码 | 情况 | 退出码 | diff --git a/rules/03-testing.md b/rules/03-testing.md index 6e92bef..af7ca41 100644 --- a/rules/03-testing.md +++ b/rules/03-testing.md @@ -1,7 +1,7 @@ # 03 · 测试与验收 > 定位:改 CLI 设施时跑什么、什么算通过。 -> 适用版本:0.4.x +> 适用版本:0.5.x > 关系:协议见 [`02-runner`](./02-runner.md);发布检查见 [`04-release`](./04-release.md)。 --- diff --git a/rules/04-release.md b/rules/04-release.md index 5794eea..83b0e5d 100644 --- a/rules/04-release.md +++ b/rules/04-release.md @@ -1,7 +1,7 @@ # 04 · 版本与发布 > 定位:CLI 设施的编译 ESM 形态、发布顺序与检查。 -> 适用版本:0.4.x +> 适用版本:0.5.x > 关系:测试见 [`03-testing`](./03-testing.md)。 --- diff --git a/rules/README.md b/rules/README.md index 4db4d39..aaa4f91 100644 --- a/rules/README.md +++ b/rules/README.md @@ -1,7 +1,7 @@ # cli · 开发规则 > 定位:本包开发规范的索引。只写判断、边界与反例;API 事实以 README 为准。 -> 适用版本:0.4.x +> 适用版本:0.5.x > owner:维护者(repo owner)· 复核:2026-11-11 · 到期降级为参考 > 关系:入口见 [`AGENTS.md`](../AGENTS.md);怎么用见 [`README.md`](../README.md)。 diff --git a/src/context.ts b/src/context.ts index 991a136..c5e2e29 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,9 +1,13 @@ +import { supportsColor } from './style.ts' + /** 命令上下文:把「往哪写、怎么写」抽出来,测试里换成内存收集器即可,不用起子进程。 */ export interface CliContext { /** 工作目录:配置与产物路径都相对它解析 */ cwd: string out: (line: string) => void err: (line: string) => void + /** 是否启用颜色;未设置视为关闭,测试与管道输出默认无色 */ + color?: boolean } export function processContext(): CliContext { @@ -11,5 +15,6 @@ export function processContext(): CliContext { cwd: process.cwd(), out: (line) => console.log(line), err: (line) => console.error(line), + color: supportsColor(process.stderr), } } diff --git a/src/index.ts b/src/index.ts index 335ec4d..b65644d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,3 +19,4 @@ export { type CliErrorShape, } from './error.ts' export { reportError, runCli, type CliSpec, type CommandSpec } from './run.ts' +export { style, supportsColor, type StyleFormat } from './style.ts' diff --git a/src/run.ts b/src/run.ts index 8ec129a..ad43687 100644 --- a/src/run.ts +++ b/src/run.ts @@ -8,6 +8,7 @@ import { parseArgs, type FlagSpec, type ParsedArgs } from './args.ts' import { processContext, type CliContext } from './context.ts' import { CliError, EXIT_OK, EXIT_USAGE, exitCodeOf, toErrorShape } from './error.ts' +import { style } from './style.ts' export interface CommandSpec { /** 单条命令的 help;可以是函数,按 positional 生成二级帮助 */ @@ -130,9 +131,10 @@ export function reportError(ctx: CliContext, error: unknown, json: boolean): voi return } - ctx.err(`✗ ${shape.message}`) - if (shape.path) ctx.err(` 位置:${shape.path}`) - if (shape.hint) ctx.err(` 提示:${shape.hint}`) + const label = shape.code && shape.code !== 'ERROR' ? ` ${style(ctx.color, 'dim', `[${shape.code}]`)}` : '' + ctx.err(`${style(ctx.color, 'red', '✗')}${label} ${shape.message}`) + if (shape.path) ctx.err(` ${style(ctx.color, 'dim', '位置:')}${shape.path}`) + if (shape.hint) ctx.err(` ${style(ctx.color, 'dim', '提示:')}${shape.hint}`) } export async function runCli(spec: CliSpec, argv: string[], ctx: CliContext = processContext()): Promise { diff --git a/src/style.ts b/src/style.ts new file mode 100644 index 0000000..2c36e3f --- /dev/null +++ b/src/style.ts @@ -0,0 +1,28 @@ +export type StyleFormat = 'red' | 'yellow' | 'dim' + +const CODES: Record = { + red: '\u001b[31m', + yellow: '\u001b[33m', + dim: '\u001b[2m', +} +const RESET = '\u001b[0m' + +/** 颜色优先级:FORCE_COLOR > NO_COLOR / NODE_DISABLE_COLORS > TERM > TTY。 */ +export function supportsColor( + stream: { isTTY?: boolean } = process.stderr, + env: NodeJS.ProcessEnv = process.env, +): boolean { + const force = env.FORCE_COLOR + if (force !== undefined) return force !== '0' && force !== 'false' + if (env.NO_COLOR || env.NODE_DISABLE_COLORS) return false + if (env.TERM === 'dumb') return false + return Boolean(stream.isTTY) +} + +/** + * 颜色只由调用方决定;只保留 error / warn / 弱化三个语义色。 + * 自研 ANSI,不引着色库,也不依赖运行时着色实现。 + */ +export function style(enabled: boolean | undefined, format: StyleFormat, text: string): string { + return enabled ? `${CODES[format]}${text}${RESET}` : text +} diff --git a/tests/infra.test.ts b/tests/infra.test.ts index f768113..cea7d39 100644 --- a/tests/infra.test.ts +++ b/tests/infra.test.ts @@ -10,15 +10,22 @@ import { parseArgs, reportError, runCli, + style, + supportsColor, type CliContext, type CliSpec, type ParsedArgs, } from '../src/index.ts' -function collector() { +function collector(color?: boolean) { const out: string[] = [] const err: string[] = [] - const ctx: CliContext = { cwd: '/demo', out: (line) => out.push(line), err: (line) => err.push(line) } + const ctx: CliContext = { + cwd: '/demo', + out: (line) => out.push(line), + err: (line) => err.push(line), + ...(color === undefined ? {} : { color }), + } return { ctx, out, err } } @@ -299,7 +306,7 @@ describe('cli · 声明与校验', () => { it('异步异常也走统一错误输出', async () => { const { ctx, err } = collector() expect(await runCli(strict, ['boom'], ctx)).toBe(EXIT_USAGE) - expect(err.join('\n')).toContain('✗ 部署失败') + expect(err.join('\n')).toContain('✗ [DEPLOY] 部署失败') }) it('mapError 把领域错误转成 CliError', async () => { @@ -372,7 +379,44 @@ describe('cli · 辅助出口', () => { expect(exitCodeOf(new CliError('bad', { code: 'USAGE' }))).toBe(EXIT_USAGE) reportError(ctx, new CliError('缺少 --config', { code: 'USAGE', path: '--config', hint: '补上' }), false) - expect(err).toEqual(['✗ 缺少 --config', ' 位置:--config', ' 提示:补上']) + expect(err).toEqual(['✗ [USAGE] 缺少 --config', ' 位置:--config', ' 提示:补上']) + }) + + it('text 错误显示稳定 code,普通异常省略 ERROR', () => { + const coded = collector() + reportError(coded.ctx, new CliError('缺少 --config', { code: 'CONFIG', details: { file: 'a.json' } }), false) + expect(coded.err).toEqual(['✗ [CONFIG] 缺少 --config']) + + const plain = collector() + reportError(plain.ctx, new Error('boom'), false) + expect(plain.err).toEqual(['✗ boom']) + }) + + it('颜色由 ctx.color 注入,默认无色', () => { + const colored = collector(true) + reportError(colored.ctx, new CliError('缺少 --config', { code: 'USAGE', path: '--config', hint: '补上' }), false) + expect(colored.err[0]).toContain('\u001b[') + expect(colored.err[0]).toContain('[USAGE]') + + const plain = collector(false) + reportError(plain.ctx, new CliError('缺少 --config', { code: 'USAGE' }), false) + expect(plain.err).toEqual(['✗ [USAGE] 缺少 --config']) + }) +}) + +describe('cli · 终端样式', () => { + it('style 只在启用时着色', () => { + expect(style(false, 'red', 'x')).toBe('x') + expect(style(undefined, 'dim', 'x')).toBe('x') + expect(style(true, 'red', 'x')).toContain('\u001b[') + }) + + it('supportsColor 按环境与 TTY 判定', () => { + expect(supportsColor({ isTTY: true }, {})).toBe(true) + expect(supportsColor({ isTTY: false }, {})).toBe(false) + expect(supportsColor({ isTTY: false }, { FORCE_COLOR: '1' })).toBe(true) + expect(supportsColor({ isTTY: true }, { NO_COLOR: '1' })).toBe(false) + expect(supportsColor({ isTTY: true }, { TERM: 'dumb' })).toBe(false) }) }) @@ -453,7 +497,7 @@ describe('cli · 运行时', () => { it('CliError 带码、位置与提示,默认退出码 2', async () => { const { ctx, err } = collector() expect(await runCli(spec, ['usage'], ctx)).toBe(2) - expect(err).toEqual(['✗ 缺少 --config', ' 位置:--config', ' 提示:补上 --config ']) + expect(err).toEqual(['✗ [USAGE] 缺少 --config', ' 位置:--config', ' 提示:补上 --config ']) }) it('CliError 可覆盖退出码', async () => {