/**
* Output formatting utilities for CLI.
*/
export type OutputFormat = 'json' | 'table' | 'pretty';
/**
* Format data for output.
*/
export function formatOutput(data: unknown, format: OutputFormat): string {
switch (format) {
case 'json':
return JSON.stringify(data, null, 2);
case 'pretty':
return JSON.stringify(data, null, 2);
case 'table':
// Table formatting is handled by cli-table3 in each command
return String(data);
default:
return String(data);
}
}
/**
* Truncate a string to a maximum length.
*/
export function truncate(str: string, maxLength: number): string {
if (str.length <= maxLength) {
return str;
}
return str.substring(0, maxLength - 3) + '...';
}
/**
* Format a date relative to now.
*/
export function formatRelativeDate(date: Date): string {
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffSecs = Math.floor(diffMs / 1000);
const diffMins = Math.floor(diffSecs / 60);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
if (diffDays > 0) {
return `${diffDays}d ago`;
}
if (diffHours > 0) {
return `${diffHours}h ago`;
}
if (diffMins > 0) {
return `${diffMins}m ago`;
}
return 'just now';
}
/**
* Format bytes to human-readable size.
*/
export function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
}
/**
* Format duration in milliseconds to human-readable string.
*/
export function formatDuration(ms: number): string {
if (ms < 1000) {
return `${ms}ms`;
}
if (ms < 60000) {
return `${(ms / 1000).toFixed(1)}s`;
}
const mins = Math.floor(ms / 60000);
const secs = Math.floor((ms % 60000) / 1000);
return `${mins}m ${secs}s`;
}