|
| 1 | +/* |
| 2 | + * Copyright (c) 2023, salesforce.com, inc. |
| 3 | + * All rights reserved. |
| 4 | + * Licensed under the BSD 3-Clause license. |
| 5 | + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause |
| 6 | + */ |
| 7 | +import { inspect } from 'node:util'; |
| 8 | +import chalk from 'chalk'; |
| 9 | + |
| 10 | +/* eslint-disable @typescript-eslint/no-explicit-any */ |
| 11 | + |
| 12 | +function pp(obj: any): any { |
| 13 | + if (typeof obj === 'string' || typeof obj === 'number') return obj; |
| 14 | + if (typeof obj === 'object') { |
| 15 | + return ( |
| 16 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument |
| 17 | + Object.keys(obj) |
| 18 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access |
| 19 | + .map((k) => k + ': ' + inspect(obj[k])) |
| 20 | + .join(', ') |
| 21 | + ); |
| 22 | + } |
| 23 | + |
| 24 | + return inspect(obj); |
| 25 | +} |
| 26 | + |
| 27 | +// @oclif/core v4 will have native support for coloring JSON so we won't need this then. |
| 28 | +export default function styledObject(obj: any, keys?: string[]): string { |
| 29 | + const output: string[] = []; |
| 30 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument |
| 31 | + const keyLengths = Object.keys(obj).map((key) => key.toString().length); |
| 32 | + const maxKeyLength = Math.max(...keyLengths) + 2; |
| 33 | + |
| 34 | + const logKeyValue = (key: string, value: any): string => |
| 35 | + `${chalk.blue(key)}:` + ' '.repeat(maxKeyLength - key.length - 1) + pp(value); |
| 36 | + |
| 37 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument |
| 38 | + for (const key of keys ?? Object.keys(obj).sort()) { |
| 39 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access |
| 40 | + const value = obj[key]; |
| 41 | + if (Array.isArray(value)) { |
| 42 | + if (value.length > 0) { |
| 43 | + output.push(logKeyValue(key, value[0])); |
| 44 | + for (const e of value.slice(1)) { |
| 45 | + output.push(' '.repeat(maxKeyLength) + pp(e)); |
| 46 | + } |
| 47 | + } |
| 48 | + } else if (value !== null && value !== undefined) { |
| 49 | + output.push(logKeyValue(key, value)); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return output.join('\n'); |
| 54 | +} |
0 commit comments