UNPKG

2.29 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2015-present, Facebook, Inc.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8'use strict';
9
10const chalk = require('chalk');
11const table = require('text-table');
12
13function isError(message) {
14 if (message.fatal || message.severity === 2) {
15 return true;
16 }
17 return false;
18}
19
20function formatter(results) {
21 let output = '\n';
22 let hasErrors = false;
23 let reportContainsErrorRuleIDs = false;
24
25 results.forEach(result => {
26 let messages = result.messages;
27 if (messages.length === 0) {
28 return;
29 }
30
31 messages = messages.map(message => {
32 let messageType;
33 if (isError(message)) {
34 messageType = 'error';
35 hasErrors = true;
36 if (message.ruleId) {
37 reportContainsErrorRuleIDs = true;
38 }
39 } else {
40 messageType = 'warn';
41 }
42
43 let line = message.line || 0;
44 let position = chalk.bold('Line ' + line + ':');
45 return [
46 '',
47 position,
48 messageType,
49 message.message.replace(/\.$/, ''),
50 chalk.underline(message.ruleId || ''),
51 ];
52 });
53
54 // if there are error messages, we want to show only errors
55 if (hasErrors) {
56 messages = messages.filter(m => m[2] === 'error');
57 }
58
59 // add color to rule keywords
60 messages.forEach(m => {
61 m[4] = m[2] === 'error' ? chalk.red(m[4]) : chalk.yellow(m[4]);
62 m.splice(2, 1);
63 });
64
65 let outputTable = table(messages, {
66 align: ['l', 'l', 'l'],
67 stringLength(str) {
68 return chalk.stripColor(str).length;
69 },
70 });
71
72 output += `${outputTable}\n\n`;
73 });
74
75 if (reportContainsErrorRuleIDs) {
76 // Unlike with warnings, we have to do it here.
77 // We have similar code in react-scripts for warnings,
78 // but warnings can appear in multiple files so we only
79 // print it once at the end. For errors, however, we print
80 // it here because we always show at most one error, and
81 // we can only be sure it's an ESLint error before exiting
82 // this function.
83 output +=
84 'Search for the ' +
85 chalk.underline(chalk.red('keywords')) +
86 ' to learn more about each error.';
87 }
88
89 return output;
90}
91
92module.exports = formatter;