From 7d91d70a1444e13c850471367a9692cad444a0ab Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 21 Jun 2026 19:28:31 +0800 Subject: [PATCH] feat(cli): add @shumai/tableprinter package to handle terminal-friendly table layouts --- apps/cli/package.json | 1 + apps/cli/src/commands/commands.test.ts | 12 +- apps/cli/src/commands/ls.ts | 41 ++-- apps/cli/src/commands/project.ts | 29 ++- bun.lock | 11 +- packages/tableprinter/package.json | 9 + packages/tableprinter/src/index.test.ts | 106 +++++++++++ packages/tableprinter/src/index.ts | 239 ++++++++++++++++++++++++ packages/tableprinter/src/text.ts | 85 +++++++++ packages/tableprinter/tsconfig.json | 4 + tsconfig.json | 3 +- 11 files changed, 488 insertions(+), 52 deletions(-) create mode 100644 packages/tableprinter/package.json create mode 100644 packages/tableprinter/src/index.test.ts create mode 100644 packages/tableprinter/src/index.ts create mode 100644 packages/tableprinter/src/text.ts create mode 100644 packages/tableprinter/tsconfig.json diff --git a/apps/cli/package.json b/apps/cli/package.json index f1b70360..d9b91a80 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -10,6 +10,7 @@ "@shumai/api": "workspace:*", "@shumai/core": "workspace:*", "@shumai/dtos": "workspace:*", + "@shumai/tableprinter": "workspace:*", "hono": "4.12.23", "ulid": "^3.0.2" } diff --git a/apps/cli/src/commands/commands.test.ts b/apps/cli/src/commands/commands.test.ts index b78e57fa..a5bbaee6 100644 --- a/apps/cli/src/commands/commands.test.ts +++ b/apps/cli/src/commands/commands.test.ts @@ -12,6 +12,8 @@ describe('CLI Commands', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any let logSpy: any // eslint-disable-next-line @typescript-eslint/no-explicit-any + let writeSpy: any + // eslint-disable-next-line @typescript-eslint/no-explicit-any let errorSpy: any // eslint-disable-next-line @typescript-eslint/no-explicit-any let exitSpy: any @@ -48,6 +50,7 @@ describe('CLI Commands', () => { beforeEach(() => { vi.resetAllMocks() logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + writeSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true) errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) exitSpy = vi .spyOn(process, 'exit') @@ -60,6 +63,7 @@ describe('CLI Commands', () => { afterEach(() => { logSpy.mockRestore() + writeSpy.mockRestore() errorSpy.mockRestore() exitSpy.mockRestore() }) @@ -82,8 +86,8 @@ describe('CLI Commands', () => { expect(mockClient.api.projects.$get).toHaveBeenCalledWith({ query: { first: '200' }, }) - expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Proj 1')) - expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Proj 2')) + expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('Proj 1')) + expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('Proj 2')) }) }) @@ -108,8 +112,8 @@ describe('CLI Commands', () => { await ls('parentId123') expect(mockClient.api.folders[':folderId'].children.$get).toHaveBeenCalledTimes(2) - expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Sub 1')) - expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('doc.pdf')) + expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('Sub 1')) + expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('doc.pdf')) }) }) diff --git a/apps/cli/src/commands/ls.ts b/apps/cli/src/commands/ls.ts index daa66603..25549fb7 100644 --- a/apps/cli/src/commands/ls.ts +++ b/apps/cli/src/commands/ls.ts @@ -1,3 +1,4 @@ +import { newTablePrinter, withTruncate } from '@shumai/tableprinter' import type { AssetInfo } from '@shumai/dtos' import { getClient } from '../client' @@ -61,38 +62,24 @@ export async function ls(parentId: string) { return } - const idWidth = 26 - const nameWidth = 35 - const typeWidth = 10 - const sizeWidth = 12 + const isTty = process.stdout.isTTY + const maxWidth = process.stdout.columns || 80 + const tp = newTablePrinter(process.stdout, isTty, maxWidth) - console.log( - 'ID'.padEnd(idWidth) + - ' | ' + - 'Name'.padEnd(nameWidth) + - ' | ' + - 'Type'.padEnd(typeWidth) + - ' | ' + - 'Size'.padEnd(sizeWidth), - ) - console.log('-'.repeat(idWidth + nameWidth + typeWidth + sizeWidth + 9)) + tp.addHeader(['ID', 'Name', 'Type', 'Size']) for (const item of items) { - const id = item.id || '' - const name = item.name || '' - const type = item.typeDisplay - const size = item.typeDisplay === 'folder' ? '-' : formatSize(item.sizeByte || 0) - - console.log( - id.padEnd(idWidth) + - ' | ' + - name.padEnd(nameWidth) + - ' | ' + - type.padEnd(typeWidth) + - ' | ' + - size.padEnd(sizeWidth), + tp.addField(item.id || '', withTruncate(null)) + tp.addField(item.name || '') + tp.addField(item.typeDisplay, withTruncate(null)) + tp.addField( + item.typeDisplay === 'folder' ? '-' : formatSize(item.sizeByte || 0), + withTruncate(null), ) + tp.endRow() } + + tp.render() } catch (err) { console.error('Error connecting to API server:', err instanceof Error ? err.message : err) process.exit(1) diff --git a/apps/cli/src/commands/project.ts b/apps/cli/src/commands/project.ts index 8a935ad2..0735bf43 100644 --- a/apps/cli/src/commands/project.ts +++ b/apps/cli/src/commands/project.ts @@ -1,3 +1,4 @@ +import { newTablePrinter } from '@shumai/tableprinter' import { getClient } from '../client' export async function projectLs() { @@ -20,28 +21,20 @@ export async function projectLs() { return } - const idWidth = 26 - const nameWidth = 30 - const rootWidth = 26 + const isTty = process.stdout.isTTY + const maxWidth = process.stdout.columns || 80 + const tp = newTablePrinter(process.stdout, isTty, maxWidth) - console.log( - 'ID'.padEnd(idWidth) + - ' | ' + - 'Name'.padEnd(nameWidth) + - ' | ' + - 'Root Folder ID'.padEnd(rootWidth), - ) - console.log('-'.repeat(idWidth + nameWidth + rootWidth + 6)) + tp.addHeader(['ID', 'Name', 'Root Folder ID']) for (const p of projects) { - const id = p.id || '' - const name = p.name || '' - const rootFolder = p.rootFolder || '' - - console.log( - id.padEnd(idWidth) + ' | ' + name.padEnd(nameWidth) + ' | ' + rootFolder.padEnd(rootWidth), - ) + tp.addField(p.id || '') + tp.addField(p.name || '') + tp.addField(p.rootFolder || '') + tp.endRow() } + + tp.render() } catch (err) { console.error('Error connecting to API server:', err instanceof Error ? err.message : err) process.exit(1) diff --git a/bun.lock b/bun.lock index 845cede5..d898157a 100644 --- a/bun.lock +++ b/bun.lock @@ -42,7 +42,7 @@ "@shumai/workflow-core": "workspace:*", }, }, - "apps/shumai-cli": { + "apps/cli": { "name": "@shumai/cli", "version": "0.0.10", "bin": { @@ -52,6 +52,7 @@ "@shumai/api": "workspace:*", "@shumai/core": "workspace:*", "@shumai/dtos": "workspace:*", + "@shumai/tableprinter": "workspace:*", "hono": "4.12.23", "ulid": "^3.0.2", }, @@ -171,6 +172,10 @@ "zod": "4.4.3", }, }, + "packages/tableprinter": { + "name": "@shumai/tableprinter", + "version": "0.0.10", + }, "packages/transcode": { "name": "@shumai/transcode", "version": "0.0.10", @@ -982,7 +987,7 @@ "@shumai/api": ["@shumai/api@workspace:packages/api"], - "@shumai/cli": ["@shumai/cli@workspace:apps/shumai-cli"], + "@shumai/cli": ["@shumai/cli@workspace:apps/cli"], "@shumai/core": ["@shumai/core@workspace:packages/core"], @@ -990,6 +995,8 @@ "@shumai/dtos": ["@shumai/dtos@workspace:packages/dtos"], + "@shumai/tableprinter": ["@shumai/tableprinter@workspace:packages/tableprinter"], + "@shumai/transcode": ["@shumai/transcode@workspace:packages/transcode"], "@shumai/transcode-app": ["@shumai/transcode-app@workspace:apps/transcode"], diff --git a/packages/tableprinter/package.json b/packages/tableprinter/package.json new file mode 100644 index 00000000..2c74faa4 --- /dev/null +++ b/packages/tableprinter/package.json @@ -0,0 +1,9 @@ +{ + "name": "@shumai/tableprinter", + "version": "0.0.10", + "private": true, + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "dependencies": {} +} diff --git a/packages/tableprinter/src/index.test.ts b/packages/tableprinter/src/index.test.ts new file mode 100644 index 00000000..6c991a19 --- /dev/null +++ b/packages/tableprinter/src/index.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from 'vitest' +import { newTablePrinter, withTruncate, withColor } from './index' + +class StringWriter { + content = '' + write(s: string) { + this.content += s + } +} + +describe('tableprinter', () => { + it('tsv mode', () => { + const writer = new StringWriter() + const tp = newTablePrinter(writer, false, 80) + + tp.addHeader(['ID', 'Name', 'Size']) + tp.addField('1') + tp.addField('apple') + tp.addField('10') + tp.endRow() + tp.addField('2') + tp.addField('banana') + tp.addField('20') + tp.endRow() + tp.render() + + expect(writer.content).toBe('1\tapple\t10\n2\tbanana\t20\n') + }) + + it('tty mode - no truncation', () => { + const writer = new StringWriter() + const tp = newTablePrinter(writer, true, 80) + + tp.addHeader(['ID', 'Name', 'Size']) + tp.addField('1') + tp.addField('apple') + tp.addField('10') + tp.endRow() + tp.addField('2') + tp.addField('banana') + tp.addField('20') + tp.endRow() + tp.render() + + const lines = writer.content.split('\n') + expect(lines[0]).toBe('ID Name Size') + expect(lines[1]).toBe('1 apple 10') + expect(lines[2]).toBe('2 banana 20') + }) + + it('tty mode - dynamic truncation to fit viewport', () => { + const writer = new StringWriter() + // Very narrow viewport + const tp = newTablePrinter(writer, true, 20) + + tp.addHeader(['ID', 'LongName']) + tp.addField('01KV') + tp.addField('YTDown_YouTube_Ed-Sheeran-Pokemon-Celestial') + tp.endRow() + tp.render() + + const lines = writer.content.split('\n').filter(Boolean) + // Avail width for columns: 20 - 2 (delimiter size) = 18. + // ID column is 4 chars, leaving 14 chars for LongName. + // LongName has truncate by default. + expect(lines[0]).toBe('ID LongName') + expect(lines[1]).toBe('01KV YTDown_YouT...') + }) + + it('tty mode - disabled truncation option', () => { + const writer = new StringWriter() + // Narrow viewport + const tp = newTablePrinter(writer, true, 25) + + // Disable truncation on the first column, keep default on the second + tp.addHeader(['ID', 'LongName'], withTruncate(null)) + tp.addField('01KVFW2HD6CK9D9H77A341HQP1', withTruncate(null)) + tp.addField('YTDown_YouTube_Ed-Sheeran-Pokemon') + tp.endRow() + tp.render() + + const lines = writer.content.split('\n').filter(Boolean) + // First column is 26 characters and must not be truncated since truncation is disabled. + expect(lines[1].startsWith('01KVFW2HD6CK9D9H77A341HQP1')).toBe(true) + }) + + it('tty mode - color preservation and display width measurement', () => { + const writer = new StringWriter() + const tp = newTablePrinter(writer, true, 80) + + // Red colored title + const coloredName = '\u001b[31mapple\u001b[0m' + tp.addHeader(['ID', 'Name']) + tp.addField('1') + tp.addField( + coloredName, + withColor((s) => `\u001b[31m${s}\u001b[0m`), + ) + tp.endRow() + tp.render() + + const lines = writer.content.split('\n') + // Display width of coloredName should be 5 despite escape sequences. + expect(lines[0]).toBe('ID Name') + }) +}) diff --git a/packages/tableprinter/src/index.ts b/packages/tableprinter/src/index.ts new file mode 100644 index 00000000..abc2b018 --- /dev/null +++ b/packages/tableprinter/src/index.ts @@ -0,0 +1,239 @@ +import { displayWidth, padRight, truncate } from './text' + +export interface TableField { + text: string + truncateFunc?: (width: number, val: string) => string + paddingFunc?: (width: number, val: string) => string + colorFunc?: (val: string) => string +} + +export type FieldOption = (field: TableField) => void + +export interface TablePrinter { + addHeader(columns: string[], ...opts: FieldOption[]): void + addField(s: string, ...opts: FieldOption[]): void + endRow(): void + render(): void +} + +export function withTruncate(fn: ((width: number, val: string) => string) | null): FieldOption { + return (f: TableField) => { + f.truncateFunc = fn ?? undefined + } +} + +export function withPadding(fn: ((width: number, val: string) => string) | null): FieldOption { + return (f: TableField) => { + f.paddingFunc = fn ?? undefined + } +} + +export function withColor(fn: (val: string) => string): FieldOption { + return (f: TableField) => { + f.colorFunc = fn + } +} + +export interface Writer { + write(s: string): void +} + +export function newTablePrinter(w: Writer, isTty: boolean, maxWidth: number): TablePrinter { + if (isTty) { + return new TtyTablePrinter(w, maxWidth) + } + return new TsvTablePrinter(w) +} + +class TtyTablePrinter implements TablePrinter { + private hasHeaders = false + private rows: TableField[][] = [] + + constructor( + private out: Writer, + private maxWidth: number, + ) {} + + addHeader(columns: string[], ...opts: FieldOption[]): void { + if (this.hasHeaders) return + this.hasHeaders = true + for (const column of columns) { + this.addField(column, ...opts) + } + this.endRow() + } + + addField(s: string, ...opts: FieldOption[]): void { + if (this.rows.length === 0) { + this.rows.push([]) + } + const rowI = this.rows.length - 1 + const field: TableField = { + text: s, + truncateFunc: truncate, + } + for (const opt of opts) { + opt(field) + } + this.rows[rowI].push(field) + } + + endRow(): void { + this.rows.push([]) + } + + render(): void { + // Filter out trailing empty rows if any + const activeRows = this.rows.filter((row) => row.length > 0) + if (activeRows.length === 0) return + + const delim = ' ' + const numCols = activeRows[0].length + const colWidths = this.calculateColumnWidths(activeRows, delim.length) + + for (const row of activeRows) { + for (let col = 0; col < row.length; col++) { + if (col >= numCols) break + const field = row[col] + if (col > 0) { + this.out.write(delim) + } + + let truncVal = field.text + if (field.truncateFunc) { + truncVal = field.truncateFunc(colWidths[col], field.text) + } + + if (field.paddingFunc) { + truncVal = field.paddingFunc(colWidths[col], truncVal) + } else if (col < numCols - 1) { + truncVal = padRight(colWidths[col], truncVal) + } + + if (field.colorFunc) { + truncVal = field.colorFunc(truncVal) + } + + this.out.write(truncVal) + } + if (row.length > 0) { + this.out.write('\n') + } + } + } + + private calculateColumnWidths(activeRows: TableField[][], delimSize: number): number[] { + const numCols = activeRows[0].length + const maxColWidths = new Array(numCols).fill(0) + const colWidths = new Array(numCols).fill(0) + + for (const row of activeRows) { + for (let col = 0; col < row.length; col++) { + if (col >= numCols) break + const field = row[col] + const w = displayWidth(field.text) + if (w > maxColWidths[col]) { + maxColWidths[col] = w + } + // if this field has disabled truncating, ensure that the column is wide enough + if (field.truncateFunc === undefined && w > colWidths[col]) { + colWidths[col] = w + } + } + } + + const getAvailWidth = (): number => { + let setWidths = 0 + for (let col = 0; col < numCols; col++) { + setWidths += colWidths[col] + } + return this.maxWidth - delimSize * (numCols - 1) - setWidths + } + + const getNumFixedCols = (): number => { + let fixedCols = 0 + for (let col = 0; col < numCols; col++) { + if (colWidths[col] > 0) { + fixedCols++ + } + } + return fixedCols + } + + // set the widths of short columns + let w = getAvailWidth() + if (w > 0) { + const numFlexColumns = numCols - getNumFixedCols() + if (numFlexColumns > 0) { + const perColumn = Math.floor(w / numFlexColumns) + for (let col = 0; col < numCols; col++) { + if (colWidths[col] === 0) { + const max = maxColWidths[col] + if (max < perColumn) { + colWidths[col] = max + } + } + } + } + } + + // truncate long columns to the remaining available width + w = getAvailWidth() + const numFlexColsCount = numCols - getNumFixedCols() + if (numFlexColsCount > 0) { + const perColumn = Math.floor(w / numFlexColsCount) + for (let col = 0; col < numCols; col++) { + if (colWidths[col] === 0) { + const max = maxColWidths[col] + if (max < perColumn) { + colWidths[col] = max + } else if (perColumn > 0) { + colWidths[col] = perColumn + } + } + } + } + + // add the remainder to truncated columns + w = getAvailWidth() + if (w > 0) { + for (let col = 0; col < numCols; col++) { + const d = maxColWidths[col] - colWidths[col] + let toAdd = w + if (d < toAdd) { + toAdd = d + } + colWidths[col] += toAdd + w -= toAdd + if (w <= 0) { + break + } + } + } + + return colWidths + } +} + +class TsvTablePrinter implements TablePrinter { + private currentCol = 0 + + constructor(private out: Writer) {} + + addHeader(): void {} + + addField(s: string): void { + if (this.currentCol > 0) { + this.out.write('\t') + } + this.out.write(s) + this.currentCol++ + } + + endRow(): void { + this.out.write('\n') + this.currentCol = 0 + } + + render(): void {} +} diff --git a/packages/tableprinter/src/text.ts b/packages/tableprinter/src/text.ts new file mode 100644 index 00000000..53aca849 --- /dev/null +++ b/packages/tableprinter/src/text.ts @@ -0,0 +1,85 @@ +/* eslint-disable no-control-regex */ +export function stripAnsi(str: string): string { + return str.replace( + /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, + '', + ) +} + +export function displayWidth(str: string): number { + const stripped = stripAnsi(str) + let width = 0 + for (let i = 0; i < stripped.length; i++) { + const code = stripped.charCodeAt(i) + // Basic detection for CJK Unified Ideographs, Hangul, Hiragana, Katakana, Fullwidth + if ( + (code >= 0x3000 && code <= 0x9fff) || // CJK symbols, Hiragana, Katakana, Unified Ideographs + (code >= 0xff00 && code <= 0xffef) || // Fullwidth forms + (code >= 0x1100 && code <= 0x11ff) || // Hangul Jamo + (code >= 0xac00 && code <= 0xd7af) // Hangul Syllables + ) { + width += 2 + } else { + width += 1 + } + } + return width +} + +export function truncate(width: number, s: string): string { + const stripped = stripAnsi(s) + const visualWidth = displayWidth(stripped) + if (visualWidth <= width) { + return s + } + + // If width is too small, return part of ellipses + if (width <= 3) { + return '.'.repeat(width) + } + + const targetWidth = width - 3 // save space for "..." + let currentWidth = 0 + let cutIndex = 0 + + for (let i = 0; i < s.length; i++) { + // If we hit an ANSI escape sequence, skip it in width calculation but keep it in output + if (s[i] === '\u001b') { + // Find end of ANSI sequence + const match = s + .slice(i) + .match(/^[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/) + if (match) { + i += match[0].length - 1 + continue + } + } + + const code = s.charCodeAt(i) + const charWidth = + (code >= 0x3000 && code <= 0x9fff) || + (code >= 0xff00 && code <= 0xffef) || + (code >= 0x1100 && code <= 0x11ff) || + (code >= 0xac00 && code <= 0xd7af) + ? 2 + : 1 + + if (currentWidth + charWidth > targetWidth) { + cutIndex = i + break + } + currentWidth += charWidth + } + + const sliced = s.slice(0, cutIndex) + const resetCode = s.includes('\u001b') ? '\u001b[0m' : '' + return sliced + '...' + resetCode +} + +export function padRight(width: number, s: string): string { + const currentWidth = displayWidth(s) + if (currentWidth >= width) { + return s + } + return s + ' '.repeat(width - currentWidth) +} diff --git a/packages/tableprinter/tsconfig.json b/packages/tableprinter/tsconfig.json new file mode 100644 index 00000000..52d43eaa --- /dev/null +++ b/packages/tableprinter/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src/**/*"] +} diff --git a/tsconfig.json b/tsconfig.json index 1cc46ed6..5a23a2e0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -25,7 +25,8 @@ "@shumai/agent/src/*": ["./packages/agent/src/*"], "@shumai/transcode": ["./packages/transcode/src/index.ts"], "@shumai/transcode/src/*": ["./packages/transcode/src/*"], - "@shumai/cli": ["./apps/cli/src/index.ts"] + "@shumai/cli": ["./apps/cli/src/index.ts"], + "@shumai/tableprinter": ["./packages/tableprinter/src/index.ts"] } }, "exclude": ["node_modules"]