eslintFormatter.js 2.06 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
'use strict';

const chalk = require('chalk');
const table = require('text-table');

function isError(message) {
  if (message.fatal || message.severity === 2) {
    return true;
  }
  return false;
}

function formatter(results) {
  let output = '\n';
Dan Abramov's avatar
Dan Abramov committed
15
  let hasErrors = false;
16
  let reportContainsErrorRuleIDs = false;
17
18
19
20
21
22
23
24
25
26
27
28

  results.forEach(result => {
    let messages = result.messages;
    if (messages.length === 0) {
      return;
    }

    messages = messages.map(message => {
      let messageType;
      if (isError(message)) {
        messageType = 'error';
        hasErrors = true;
29
30
31
        if (message.ruleId) {
          reportContainsErrorRuleIDs = true;
        }
32
33
34
35
36
      } else {
        messageType = 'warn';
      }

      let line = message.line || 0;
37
      let position = chalk.bold('Line ' + line + ':');
38
39
40
41
42
      return [
        '',
        position,
        messageType,
        message.message.replace(/\.$/, ''),
43
        chalk.underline(message.ruleId || ''),
44
45
46
47
48
49
50
51
      ];
    });

    // if there are error messages, we want to show only errors
    if (hasErrors) {
      messages = messages.filter(m => m[2] === 'error');
    }

52
    // add color to rule keywords
53
    messages.forEach(m => {
54
      m[4] = m[2] === 'error' ? chalk.red(m[4]) : chalk.yellow(m[4]);
55
      m.splice(2, 1);
56
57
58
59
60
61
62
63
64
65
66
67
    });

    let outputTable = table(messages, {
      align: ['l', 'l', 'l'],
      stringLength(str) {
        return chalk.stripColor(str).length;
      },
    });

    output += `${outputTable}\n\n`;
  });

68
  if (reportContainsErrorRuleIDs) {
Dan Abramov's avatar
Dan Abramov committed
69
70
71
72
73
74
75
76
77
78
79
80
    // Unlike with warnings, we have to do it here.
    // We have similar code in react-scripts for warnings,
    // but warnings can appear in multiple files so we only
    // print it once at the end. For errors, however, we print
    // it here because we always show at most one error, and
    // we can only be sure it's an ESLint error before exiting
    // this function.
    output += 'Search for the ' +
      chalk.underline(chalk.red('rule keywords')) +
      ' to learn more about each error.';
  }

81
82
83
84
  return output;
}

module.exports = formatter;