UNPKG

clever-tools

Version:

Command Line Interface for Clever Cloud.

86 lines (73 loc) 2.76 kB
import _ from 'lodash'; import { format } from 'node:util'; import { styleText } from './lib/style-text.js'; function getPrefix(severity) { const prefix = `[${severity.toUpperCase()}] `; const prefixLength = prefix.length; if (severity === 'error') { return { prefix: styleText(['bold', 'red'], prefix), prefixLength }; } return { prefix, prefixLength }; } function processApiError(error) { if (error.id == null || error.message == null) { return error; } const fields = _.map(error.fields, (msg, field) => `${field}: ${msg}`); return [`${error.message} [${error.id}]`, ...fields].join('\n'); } function formatLines(prefixLength, lines) { const blankPrefix = _.repeat(' ', prefixLength); return (lines || '') .split('\n') .map((line, i) => (i === 0 ? line : `${blankPrefix}${line}`)) .join('\n'); } function consoleErrorWithoutColor(line) { process.stderr.write(format(line) + '\n'); } export const Logger = _(['debug', 'info', 'warn', 'error']) .map((severity) => { if (process.env.CLEVER_QUIET || (!process.env.CLEVER_VERBOSE && (severity === 'debug' || severity === 'info'))) { return [severity, _.noop]; } const consoleFn = severity === 'error' ? consoleErrorWithoutColor : console.log; const { prefix, prefixLength } = getPrefix(severity); return [ severity, (err) => { const message = _.get(err, 'message', err); const formattedMsg = formatLines(prefixLength, processApiError(message)); if (process.env.CLEVER_VERBOSE && severity === 'error') { consoleErrorWithoutColor('[STACKTRACE]'); consoleErrorWithoutColor(err); consoleErrorWithoutColor('[/STACKTRACE]'); } return consoleFn(`${prefix}${formattedMsg}`); }, ]; }) .fromPairs() .value(); // No decoration for Logger.println Logger.println = console.log; /** * Prints a line of text with specified indentation. * * @param {string} text - The text to be printed. * @param {number} indentLevel - The number of spaces to indent the text. */ Logger.printlnWithIndent = (text, indentLevel) => { Logger.println(' '.repeat(indentLevel) + text); }; // Logger for success with a green check before the message Logger.printSuccess = (message) => console.log(`${styleText(['bold', 'green'], '✓')} ${message}`); // Logger for information with a blue 'i' before the message Logger.printInfo = (message) => console.log(`${styleText('blue', 'i')} ${message}`); // No decoration for Logger.println Logger.printJson = (obj) => { console.log(JSON.stringify(obj, null, 2)); }; Logger.printErrorLine = consoleErrorWithoutColor; // Only exported for testing, shouldn't be used directly Logger.processApiError = processApiError;