eslintFormatter.js 1.92 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
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

  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;
      } else {
        messageType = 'warn';
      }

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

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

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

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

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

Dan Abramov's avatar
Dan Abramov committed
64
65
66
67
68
69
70
71
72
73
74
75
76
  if (hasErrors) {
    // 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.';
  }

77
78
79
80
  return output;
}

module.exports = formatter;