UNPKG

2.28 kBJavaScriptView Raw
1/*! snazzy. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
2const chalk = require('chalk')
3const standardJson = require('standard-json')
4const stream = require('readable-stream')
5const stripAnsi = require('strip-ansi')
6const table = require('text-table')
7
8class CompactToStylishStream extends stream.Transform {
9 constructor (opts) {
10 super(opts)
11
12 this.exitCode = 0
13 this._buffer = []
14 }
15
16 _transform (chunk, encoding, cb) {
17 this._buffer.push(chunk)
18 cb(null)
19 }
20
21 _flush (cb) {
22 const lines = Buffer.concat(this._buffer).toString()
23 const jsonResults = standardJson(lines, { noisey: true })
24 const output = processResults(jsonResults)
25 this.push(output)
26
27 this.exitCode = output === '' ? 0 : 1
28 cb(null)
29 }
30}
31
32/**
33 * Given a word and a count, append an s if count is not one.
34 * @param {string} word A word in its singular form.
35 * @param {int} count A number controlling whether word should be pluralized.
36 * @returns {string} The original word with an s on the end if count is not one.
37 */
38function pluralize (word, count) {
39 return (count === 1 ? word : word + 's')
40}
41
42function processResults (results) {
43 let output = '\n'
44 let total = 0
45
46 results.forEach(function (result) {
47 const messages = result.messages
48
49 if (messages.length === 0) {
50 return
51 }
52
53 total += messages.length
54 output += chalk.underline(result.filePath) + '\n'
55
56 output += table(
57 messages.map(function (message) {
58 const messageType = chalk.red('error')
59
60 return [
61 '',
62 message.line || 0,
63 message.column || 0,
64 messageType,
65 message.message.replace(/\.$/, ''),
66 chalk.dim(message.ruleId || '')
67 ]
68 }),
69 {
70 align: ['', 'r', 'l'],
71 stringLength: function (str) {
72 return stripAnsi(str).length
73 }
74 }
75 ).split('\n').map(function (el) {
76 return el.replace(/(\d+)\s+(\d+)/, function (m, p1, p2) {
77 return chalk.dim(p1 + ':' + p2)
78 })
79 }).join('\n') + '\n\n'
80 })
81
82 if (total > 0) {
83 output += chalk.red.bold([
84 '\u2716 ', total, pluralize(' problem', total), '\n'
85 ].join(''))
86 }
87
88 return total > 0 ? output : ''
89}
90
91module.exports = CompactToStylishStream