aboutsummaryrefslogtreecommitdiff
path: root/node_modules/postcss-reporter/lib/reporter.js
blob: 70781fba073b2506a0cad7479d5babdab0042714 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
var chalk = require('chalk');
var _ = require('lodash');
var defaultFormatter = require('./formatter');
var util = require('./util');

module.exports = function(opts) {
  var options = opts || {};

  var formatter = options.formatter || defaultFormatter({
    sortByPosition: (typeof options.sortByPosition !== 'undefined') ? options.sortByPosition : true,
    positionless: options.positionless || 'first',
    noIcon: options.noIcon,
    noPlugin: options.noPlugin,
  });

  var pluginFilter;
  if (!options.plugins) {
    // Every plugin
    pluginFilter = function() { return true; };
  } else if (options.plugins.every(function(plugin) { return plugin[0] === '!'; })) {
    // Blacklist
    pluginFilter = function(message) {
      return options.plugins.indexOf('!' + message.plugin) === -1;
    };
  } else {
    // Whitelist
    pluginFilter = function(message) {
      return options.plugins.indexOf(message.plugin) !== -1;
    };
  }

  var messageFilter = options.filter || function(message) { return (message.type === 'warning'); };

  return function(css, result) {
    var messagesToLog = result.messages
      .filter(pluginFilter)
      .filter(messageFilter);

    var resultSource = (!result.root.source) ? ''
      : result.root.source.input.file || result.root.source.input.id

    var sourceGroupedMessages = _.groupBy(messagesToLog, function(message) {
      return util.getLocation(message).file || resultSource;
    });

    var report = '';
    _.forOwn(sourceGroupedMessages, function(messages, source) {
      report += formatter({
        messages: messages,
        source: source,
      });
    });

    if (options.clearReportedMessages) {
      result.messages = _.difference(result.messages, messagesToLog);
    }

    if (options.clearAllMessages) {
      var messagesToClear = result.messages.filter(pluginFilter);
      result.messages = _.difference(result.messages, messagesToClear);
    }


    if (!report) return;

    console.log(report);

    if (options.throwError && shouldThrowError()) {
      throw new Error(chalk.red.bold('\n** postcss-reporter: warnings or errors were found **'));
    }

    function shouldThrowError() {
      return (
        messagesToLog.length
        && messagesToLog.some(function(message) {
          return message.type === 'warning' || message.type === 'error';
        })
      );
    }
  };
};