eslintFormatter.js 2.36 KB
Newer Older
Dan Abramov's avatar
Dan Abramov committed
1
2
3
4
5
6
7
8
9
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

10
11
12
13
14
15
16
17
18
19
20
21
22
23
'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
24
  let hasErrors = false;
25
  let reportContainsErrorRuleIDs = false;
26
27
28
29
30
31
32
33
34
35
36
37

  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;
38
39
40
        if (message.ruleId) {
          reportContainsErrorRuleIDs = true;
        }
41
42
43
44
45
      } else {
        messageType = 'warn';
      }

      let line = message.line || 0;
46
      let position = chalk.bold('Line ' + line + ':');
47
48
49
50
51
      return [
        '',
        position,
        messageType,
        message.message.replace(/\.$/, ''),
52
        chalk.underline(message.ruleId || ''),
53
54
55
56
57
58
59
60
      ];
    });

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

61
    // add color to rule keywords
62
    messages.forEach(m => {
63
      m[4] = m[2] === 'error' ? chalk.red(m[4]) : chalk.yellow(m[4]);
64
      m.splice(2, 1);
65
66
67
68
69
70
71
72
73
74
75
76
    });

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

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

77
  if (reportContainsErrorRuleIDs) {
Dan Abramov's avatar
Dan Abramov committed
78
79
80
81
82
83
84
    // 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.
85
86
    output +=
      'Search for the ' +
Dan Abramov's avatar
Dan Abramov committed
87
      chalk.underline(chalk.red('keywords')) +
Dan Abramov's avatar
Dan Abramov committed
88
89
90
      ' to learn more about each error.';
  }

91
92
93
94
  return output;
}

module.exports = formatter;