OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-note / lib / cli / output.js

63 lines · javascript ref:
/**
 * pgh output formatting
 */

/**
 * Print aligned table
 * @param {Array<Object>} rows - Row objects
 * @param {Array<{key: string, label: string, width?: number}>} columns - Column defs
 */
export function table (rows, columns) {
  if (rows.length === 0) {
    console.log('No results.')
    return
  }

  // Calculate column widths
  const widths = columns.map(col => {
    const maxData = rows.reduce((max, row) => {
      const val = String(row[col.key] ?? '')
      return Math.max(max, val.length)
    }, 0)
    return Math.max(col.label.length, Math.min(maxData, col.width || 60))
  })

  // Header
  const header = columns.map((col, i) => col.label.padEnd(widths[i])).join('  ')
  console.log(header)
  console.log(columns.map((_, i) => '-'.repeat(widths[i])).join('  '))

  // Rows
  for (const row of rows) {
    const line = columns.map((col, i) => {
      const val = String(row[col.key] ?? '')
      return val.length > widths[i]
        ? val.slice(0, widths[i] - 1) + '\u2026'
        : val.padEnd(widths[i])
    }).join('  ')
    console.log(line)
  }
}

/**
 * Print JSON (for --json flag)
 */
export function jsonOut (data) {
  console.log(JSON.stringify(data, null, 2))
}

/**
 * Print to stdout
 */
export function log (msg) {
  console.log(msg)
}

/**
 * Print error and exit
 */
export function error (msg) {
  console.error('Error: ' + msg)
  process.exit(1)
}