diff --git a/src/commands/datasource/list.ts b/src/commands/datasource/list.ts index 67b055a..16b48cb 100644 --- a/src/commands/datasource/list.ts +++ b/src/commands/datasource/list.ts @@ -51,15 +51,15 @@ export function buildDatasourceListCommand(): Command { return ctx.success(summary) } log.info(`共 ${list.length} 个数据源`) - console.log('ID'.padEnd(30) + 'FULL_NAME'.padEnd(23) + 'ENCODE'.padEnd(21) + 'DB_TYPE') - console.log('-'.repeat(90)) - for (const d of list) { - const id = String(d.id || '').padEnd(30) - const name = String(d.fullName || '').padEnd(23) - const code = String(d.enCode || '').padEnd(21) - const type = String(d.dbType || '') - console.log(`${id}${name}${code}${type}`) - } + log.printRawTable( + ['ID', 'FULL_NAME', 'ENCODE', 'DB_TYPE'], + list.map((d) => [ + String(d.id || ''), + String(d.fullName || ''), + String(d.enCode || ''), + String(d.dbType || ''), + ]), + ) ctx.success(summary) } catch (e) { ctx.fail(`datasource list 失败: ${(e as Error).message?.slice(0, 200)}`) diff --git a/src/commands/dm/fields.ts b/src/commands/dm/fields.ts index 0b184f5..61d9ec8 100644 --- a/src/commands/dm/fields.ts +++ b/src/commands/dm/fields.ts @@ -64,16 +64,16 @@ export function buildDmFieldsCommand(): Command { return ctx.success(summary) } log.info(`表 ${opts.table} 字段数=${arr.length}`) - console.log('FIELD TYPE LENGTH NULL PK') - console.log('-'.repeat(60)) - for (const f of arr as Array>) { - const field = String(f.field || f.columnName || '').padEnd(20) - const type = String(f.dataType || '').padEnd(14) - const len = String(f.dataLength || '').padEnd(7) - const nullable = f.allowNull === 0 || f.allowNull === '0' ? 'NO' : 'YES' - const pk = f.primaryKey === 1 || f.primaryKey === '1' ? 'PK' : '' - console.log(`${field}${type}${len}${nullable.padEnd(5)}${pk}`) - } + log.printRawTable( + ['FIELD', 'TYPE', 'LENGTH', 'NULL', 'PK'], + (arr as Array>).map((f) => [ + String(f.field || f.columnName || ''), + String(f.dataType || ''), + String(f.dataLength || ''), + f.allowNull === 0 || f.allowNull === '0' ? 'NO' : 'YES', + f.primaryKey === 1 || f.primaryKey === '1' ? 'PK' : '', + ]), + ) ctx.success(summary) } catch (e) { ctx.fail(`dm fields 失败: ${(e as Error).message?.slice(0, 200)}`) diff --git a/src/commands/dm/list.ts b/src/commands/dm/list.ts index 6cb6296..34da05a 100644 --- a/src/commands/dm/list.ts +++ b/src/commands/dm/list.ts @@ -65,11 +65,10 @@ export function buildDmListCommand(): Command { return ctx.success(summary) } log.info(`dbLinkId=${dbLinkId} 共 ${list.length} 张表`) - console.log('TABLE TABLE_NAME(中文)') - console.log('-'.repeat(60)) - for (const t of list) { - console.log(`${t.table.padEnd(30)}${t.tableName || ''}`) - } + log.printRawTable( + ['TABLE', 'TABLE_NAME(中文)'], + list.map((t) => [t.table, t.tableName || '']), + ) ctx.success(summary) } catch (e) { ctx.fail(`dm list 失败: ${(e as Error).message?.slice(0, 200)}`) diff --git a/src/core/log.ts b/src/core/log.ts index 0d55a16..8750459 100644 --- a/src/core/log.ts +++ b/src/core/log.ts @@ -74,6 +74,51 @@ export const log = { if (_quiet) { _buffer.push({ level: 'debug', args }); return } console.error(`${C.dim}[debug]${C.reset}`, ...args) }, + /** + * 表格输出 (P4 v2 2026-07-21): 收口 350 处 console.log 表格散布的 consolidation 入口. + * + * 行为: 直出 stdout, 跳过 quiet 模式 (跟 log.raw 同). 输出对齐表格, 第一行 + * headers, 第二行 separator (- 重复), 之后各 rows. + * + * 用法 (逐步替代 console.log 表格): + * log.printRawTable( + * ['ID', 'FULL_NAME', 'ENCODE', 'DB_TYPE'], + * list.map(d => [String(d.id), String(d.fullName), String(d.enCode), String(d.dbType)]), + * ) + * + * 兼容性: 原 console.log 表格调用 (333 处) 仍能跑, 不阻塞. 这个 primitive 是 + * 起点, 让后续 P6 续 + P4 v3 可以批量迁移. + * + * @param headers 列名数组 + * @param rows 数据行 (每行字符串数组, 长度应跟 headers 对齐) + * @param opts.indent 缩进字符串 (默认 '') + * @param opts.maxColWidth 单列最大宽度 (默认 36, 防止 long 字段撑破) + */ + printRawTable( + headers: string[], + rows: string[][], + opts: { indent?: string; maxColWidth?: number } = {}, + ): void { + const indent = opts.indent ?? '' + const maxColWidth = opts.maxColWidth ?? 36 + // 计算每列最大宽度 (按 truncate 后) + const widths = headers.map((h, i) => { + const cellWidths = rows.map((r) => (r[i] ?? '').length) + return Math.min(maxColWidth, Math.max(h.length, ...cellWidths)) + }) + const pad = (s: string, w: number) => { + const truncated = s.length > w ? s.slice(0, w - 1) + '…' : s + return truncated.padEnd(w) + } + const headerLine = indent + headers.map((h, i) => pad(h, widths[i])).join(' ') + '\n' + const sepLine = indent + widths.map((w) => '-'.repeat(w)).join(' ') + '\n' + const body = rows + .map((r) => indent + r.map((c, i) => pad(c ?? '', widths[i])).join(' ') + '\n') + .join('') + const output = headerLine + sepLine + body + if (_quiet) { _buffer.push({ level: 'raw', args: [output] }); return } + process.stdout.write(output) + }, } const _writers: Record void> = { diff --git a/tests/unit/output_filter.test.ts b/tests/unit/output_filter.test.ts index 104b005..9c50626 100644 --- a/tests/unit/output_filter.test.ts +++ b/tests/unit/output_filter.test.ts @@ -354,3 +354,81 @@ describe('wrapCommand — 5c 收口 helper (v2.2+ 2026-07-21)', () => { } }) }) + +describe('log.printRawTable — 表格输出 primitive (P4 v2 2026-07-21)', () => { + let stdoutSpy: ReturnType + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(((_s: string) => { + // no-op + }) as never) + }) + + afterEach(() => { + stdoutSpy.mockRestore() + }) + + it('基础表格: header + separator + rows 对齐', () => { + log.printRawTable( + ['ID', 'NAME', 'TYPE'], + [ + ['123', 'myapp', 'MySQL'], + ['456', 'test', 'PG'], + ], + ) + const output = stdoutSpy.mock.calls.map((c) => String(c[0])).join('') + // header widths: ID(3) NAME(5) TYPE(5); 2-space separator + expect(output).toContain('ID') + expect(output).toContain('NAME') + expect(output).toContain('TYPE') + expect(output).toContain('--- ----- -----') // 5 dashes for NAME+TYPE + expect(output).toContain('123') + expect(output).toContain('myapp') + expect(output).toContain('MySQL') + expect(output).toContain('456') + expect(output).toContain('PG') + // 3 lines: header + separator + at least 2 data rows + expect(output.trim().split('\n').length).toBeGreaterThanOrEqual(3) + }) + + it('长字段 truncate 省略号', () => { + log.printRawTable( + ['NAME'], + [['this is a very long name that exceeds the 36 char default maxColWidth']], + ) + const output = stdoutSpy.mock.calls.map((c) => String(c[0])).join('') + expect(output).toContain('…') + // 数据行被截断到 default maxColWidth=36 char (含 '…') + const lines = output.trim().split('\n') + const dataLine = lines[lines.length - 1] // 最后一行 = 数据行 + expect(dataLine.length).toBeLessThanOrEqual(36 + 10) // 36 + 一些 padding + }) + + it('maxColWidth 自定义', () => { + log.printRawTable( + ['NAME'], + [['short'], ['much longer than twenty characters in this test']], + { maxColWidth: 20 }, + ) + const output = stdoutSpy.mock.calls.map((c) => String(c[0])).join('') + expect(output).toContain('much longer than tw…') + expect(output).toContain('short') + }) + + it('quiet mode: 写入 buffer 而非 stdout', () => { + // 进入 quiet mode (默认) + log.setQuiet(true) + log.printRawTable(['A'], [['x']]) + // quiet 模式应写到 buffer 而非 stdout + expect(stdoutSpy).not.toHaveBeenCalled() + log.setQuiet(false) + }) + + it('空 rows: 只打 header + separator', () => { + log.printRawTable(['A', 'B'], []) + const output = stdoutSpy.mock.calls.map((c) => String(c[0])).join('') + expect(output).toContain('A') + expect(output).toContain('B') + expect(output).toContain('-') // separator + }) +})