toes/src/cli/pager.ts
2026-02-10 08:09:00 -08:00

36 lines
767 B
TypeScript

export async function withPager(fn: () => Promise<void> | void): Promise<void> {
if (!process.stdout.isTTY) {
await fn()
return
}
const lines: string[] = []
const originalLog = console.log
console.log = (...args: unknown[]) => {
lines.push(args.map(a => typeof a === 'string' ? a : String(a)).join(' '))
}
try {
await fn()
} finally {
console.log = originalLog
}
if (lines.length === 0) return
const text = lines.join('\n') + '\n'
const rows = process.stdout.rows || 24
const lineCount = text.split('\n').length - 1
if (lineCount > rows) {
Bun.spawnSync(['less', '-R'], {
stdin: Buffer.from(text),
stdout: 'inherit',
stderr: 'inherit',
})
} else {
process.stdout.write(text)
}
}