UNPKG

@honor-minigame/cli

Version:

honor minigame pack cli

121 lines (112 loc) 3.62 kB
import chalk from 'chalk' import readline from 'readline' import padStart from 'string.prototype.padstart' import EventEmitter from 'events' // import { Console } from 'console' /** * 带颜色的 info, log, warn, error, trace 的打印日志输出流 */ export const colorconsole = { writable: null, init(writable) { this.writable = writable } } export const events = new EventEmitter() /** * 日志操作,通过事件总线分发,目前未使用 * @param {String} type info|warn|error|done * @param {String} tag 标签 * @param {String} message 要打印出来的消息 */ function _log(type, tag, message) { if (message) { events.emit('log', { message, type, tag }) } } const format = (label, msg) => { return msg.split('\n').map((line, i) => { return i === 0 ? `${label} ${line}` : padStart(line, chalk.reset(label).length) }).join('\n') } /** * Tag标签,使用亮黑色背景,白色字 * @param {String`} msg Tag标签的格式 */ const chalkTag = msg => chalk.bgBlackBright.white.dim(` ${msg} `) /** * 常规的log * @param {String} msg 要打印的信息 * @param {String} tag 要打印信息的标签 */ export const log = (msg = '', tag = null) => { tag ? console.log(format(chalkTag(tag), msg)) : console.log(msg) colorconsole.writable && colorconsole.writable.write(msg) _log('log', tag, msg) } /** * 常规的info。label为蓝色背景,黑色字体 * @param {String} msg 要打印的信息 * @param {String} tag 要打印信息的标签 */ export const info = (msg, tag = null) => { console.log(format(chalk.bgBlue.black(' INFO ') + (tag ? chalkTag(tag) : ''), msg)) colorconsole.writable && colorconsole.writable.write(`[INFO] ${msg}`) _log('info', tag, msg) } /** * 常规的done。label为绿色背景,黑色字体 * @param {String} msg 要打印的信息 * @param {String} msg 要打印的信息 * @param {String} tag 要打印信息的标签 */ export const done = (msg, tag = null) => { console.log(format(chalk.bgGreen.black(' DONE ') + (tag ? chalkTag(tag) : ''), msg)) colorconsole.writable && colorconsole.writable.write(`[DONE] ${msg}`) _log('done', tag, msg) } /** * 警告。label为黄色色背景,黑色字体 msg颜色为黄色 * @param {String} msg 要打印的信息 * @param {String} tag 要打印信息的标签 */ export const warn = (msg, tag = null) => { console.warn(format(chalk.bgYellow.black(' WARN ') + (tag ? chalkTag(tag) : ''), chalk.yellow(msg))) colorconsole.writable && colorconsole.writable.write(`[WARN] ${msg}`) _log('warn', tag, msg) } /** * 错误。label为红色背景,黑色字体 msg颜色为红色 * @param {String} msg 要打印的信息 * @param {String} tag 要打印信息的标签 */ export const error = (msg, tag = null) => { console.error(format(chalk.bgRed(' ERROR ') + (tag ? chalkTag(tag) : ''), chalk.red(msg))) colorconsole.writable && colorconsole.writable.write(`[ERROR] ${msg}`) _log('error', tag, msg) // 打出调用栈 if (msg instanceof Error) { _log('error', tag, msg.stack) } } /** * 清楚控制台的信息 * @param {String} title [可选] 清除控制台后的提示 */ export const clearConsole = title => { if (process.stdout.isTTY) { const blank = '\n'.repeat(process.stdout.rows) console.log(blank) readline.cursorTo(process.stdout, 0, 0) readline.clearScreenDown(process.stdout) if (title) { console.log(title) } } }