UNPKG

2.81 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 path = require('path');
11const chalk = require('chalk');
12const stripAnsi = require('strip-ansi');
13const table = require('text-table');
14
15const cwd = process.cwd();
16
17const emitErrorsAsWarnings =
18 process.env.NODE_ENV === 'development' &&
19 process.env.ESLINT_NO_DEV_ERRORS === 'true';
20
21function isError(message) {
22 if (message.fatal || message.severity === 2) {
23 return true;
24 }
25 return false;
26}
27
28function getRelativePath(filePath) {
29 return path.relative(cwd, filePath);
30}
31
32function formatter(results) {
33 let output = '\n';
34 let hasErrors = false;
35 let reportContainsErrorRuleIDs = false;
36
37 results.forEach(result => {
38 let messages = result.messages;
39 if (messages.length === 0) {
40 return;
41 }
42
43 messages = messages.map(message => {
44 let messageType;
45 if (isError(message) && !emitErrorsAsWarnings) {
46 messageType = 'error';
47 hasErrors = true;
48 if (message.ruleId) {
49 reportContainsErrorRuleIDs = true;
50 }
51 } else {
52 messageType = 'warn';
53 }
54
55 let line = message.line || 0;
56 if (message.column) {
57 line += ':' + message.column;
58 }
59 let position = chalk.bold('Line ' + line + ':');
60 return [
61 '',
62 position,
63 messageType,
64 message.message.replace(/\.$/, ''),
65 chalk.underline(message.ruleId || ''),
66 ];
67 });
68
69 // if there are error messages, we want to show only errors
70 if (hasErrors) {
71 messages = messages.filter(m => m[2] === 'error');
72 }
73
74 // add color to rule keywords
75 messages.forEach(m => {
76 m[4] = m[2] === 'error' ? chalk.red(m[4]) : chalk.yellow(m[4]);
77 m.splice(2, 1);
78 });
79
80 let outputTable = table(messages, {
81 align: ['l', 'l', 'l'],
82 stringLength(str) {
83 return stripAnsi(str).length;
84 },
85 });
86
87 // print the filename and relative path
88 output += `${getRelativePath(result.filePath)}\n`;
89
90 // print the errors
91 output += `${outputTable}\n\n`;
92 });
93
94 if (reportContainsErrorRuleIDs) {
95 // Unlike with warnings, we have to do it here.
96 // We have similar code in react-scripts for warnings,
97 // but warnings can appear in multiple files so we only
98 // print it once at the end. For errors, however, we print
99 // it here because we always show at most one error, and
100 // we can only be sure it's an ESLint error before exiting
101 // this function.
102 output +=
103 'Search for the ' +
104 chalk.underline(chalk.red('keywords')) +
105 ' to learn more about each error.';
106 }
107
108 return output;
109}
110
111module.exports = formatter;