|
| 1 | +/* |
| 2 | +Copyright 2026 Adobe. All rights reserved. |
| 3 | +This file is licensed to you under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. You may obtain a copy |
| 5 | +of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +
|
| 7 | +Unless required by applicable law or agreed to in writing, software distributed under |
| 8 | +the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS |
| 9 | +OF ANY KIND, either express or implied. See the License for the specific language |
| 10 | +governing permissions and limitations under the License. |
| 11 | +*/ |
| 12 | + |
| 13 | +/** |
| 14 | + * Print a table to stdout, replicating the ux.table output format from @oclif/core v2. |
| 15 | + * Required because ux.table was removed in @oclif/core v4. |
| 16 | + * |
| 17 | + * @param {Array<object>} data Array of row objects |
| 18 | + * @param {object} columns Column definitions keyed by object property name. |
| 19 | + * Each column may have: header (string), minWidth (number) |
| 20 | + * @param {object} [options] Options |
| 21 | + * @param {Function} [options.printLine] Function to print each line (defaults to process.stdout.write) |
| 22 | + */ |
| 23 | +function table (data, columns, options = {}) { |
| 24 | + const printLine = options.printLine || ((line) => process.stdout.write(line + '\n')) |
| 25 | + |
| 26 | + const cols = Object.entries(columns).map(([key, opts]) => { |
| 27 | + const header = opts.header || capitalize(key) |
| 28 | + const minContentWidth = opts.minWidth ? opts.minWidth - 1 : 0 |
| 29 | + const maxDataWidth = data.reduce((max, row) => { |
| 30 | + const val = String(row[key] === undefined || row[key] === null ? '' : row[key]) |
| 31 | + return Math.max(max, val.length) |
| 32 | + }, 0) |
| 33 | + const width = Math.max(header.length, maxDataWidth, minContentWidth) |
| 34 | + return { key, header, width } |
| 35 | + }) |
| 36 | + |
| 37 | + // Header row |
| 38 | + printLine(cols.map(col => ' ' + col.header.padEnd(col.width)).join('') + ' ') |
| 39 | + |
| 40 | + // Separator row |
| 41 | + printLine(cols.map(col => ' ' + '\u2500'.repeat(col.width)).join('') + ' ') |
| 42 | + |
| 43 | + // Data rows |
| 44 | + for (const row of data) { |
| 45 | + printLine(cols.map(col => { |
| 46 | + const val = String(row[col.key] === undefined || row[col.key] === null ? '' : row[col.key]) |
| 47 | + return ' ' + val.padEnd(col.width) |
| 48 | + }).join('') + ' ') |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Capitalize the first letter of a string. |
| 54 | + * |
| 55 | + * @param {string} str input string |
| 56 | + * @returns {string} string with first letter uppercased |
| 57 | + */ |
| 58 | +function capitalize (str) { |
| 59 | + return str.charAt(0).toUpperCase() + str.slice(1) |
| 60 | +} |
| 61 | + |
| 62 | +module.exports = { table } |
0 commit comments