@sap/cds-dk
Version:
Command line client and development toolkit for the SAP Cloud Application Programming Model
68 lines (60 loc) • 2.94 kB
JavaScript
const DEBUG = /\b(y|all|cli)\b/.test(process.env.DEBUG) ? console.debug : undefined
// https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
const t = module.exports.codes = {
reset: '\x1b[0m', // Default
bold: '\x1b[1m', // Bold/Bright
link: '\x1b[4m', // underline
grey: '\x1b[2m', // Supporting comment
red: '\x1b[91m', // Bright Foreground Red
green: '\x1b[32m', // Foreground Green
blue: '\x1b[34m', // Foreground Blue
yellow:'\x1b[33m', // Foreground Yellow
orange: '\x1b[38;2;255;140;0m' // darker orange, works with bright and dark background
}
Object.defineProperty(module.exports, 'isTTY', { get: () => process.stdout.isTTY && process.stderr.isTTY })
const useColor = module.exports.isTTY && process.env.NO_COLOR !== 'true' || (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== 'false')
module.exports.colors = useColor
const as = module.exports.as = (codes, o) => {
return useColor ? (codes + o + t.reset) : ('' + o)
}
const asErr = module.exports.error = o => DEBUG ? o : as(t.red + t.bold, o)
const asWarn = module.exports.warn = o => DEBUG ? o : as(t.orange + t.bold, o)
const asInfo = module.exports.info = o => DEBUG ? o : as(t.green + t.bold, o)
module.exports.warn = o => as(t.orange, o)
module.exports.info = o => as(t.green, o)
module.exports.link = o => as(t.link, o)
module.exports.bold = o => as(t.bold, o)
module.exports.highlight = o => as(t.blue,as(t.bold, o))
module.exports.dim = o => as(t.grey, o)
const format = module.exports.format = (o, severity='Error', asInternalError=false, withStack=false) => {
switch (severity) {
case 'Error' : return format.error (o, asInternalError, withStack)
case 'Warning': return format.warn (o)
default : return format.info (o)
}
}
// decorate.error, .warning, .info
// 'Error: foo' -> '[ERROR] foo' (Maven-like, allows for better grepping in logs)
Object.assign (format, {
error: (o, asInternalError, withStack) => {
if (DEBUG) return o
if (asInternalError) {
return `[${asErr('INTERNAL ERROR')}] ${o.stack || o.toString()}\nPlease report this error.\n`
}
return `[${asErr('ERROR')}] ${toString(o, 'Error', withStack)}`
},
warn: o => DEBUG ? o : `[${asWarn('WARNING')}] ${toString(o, 'Warning')}`,
info: o => DEBUG ? o : `[${asInfo('INFO')}] ${toString(o, 'Info')}`,
poorMarkdown: (md) => { return md
.replace(/\n# ([^\n]*)\n/g, `\n${as(t.bold, '$1')}\n`)
.replace(/ \*([^*]+)\*/g, ` ${as(t.bold, '$1')}`)
.replace(/ _([^_]+)_/g, ` ${as(t.link, '$1')}`)
}
})
function toString(o, severity, withStack) {
if (!o || !o.toString) return o
return (withStack && o.stack ? o.stack : o.toString())
// strips the 'Error: ' prefix in the message, so that we can add our own prefix
.replace(new RegExp('^' + severity + ': ', 'i'), '') // beginning
.replace(new RegExp(' ' + severity + ':' , 'i'), '') // middle
}