all files / src/ watcher.js

93.75% Statements 30/32
87.5% Branches 7/8
83.33% Functions 5/6
93.75% Lines 30/32
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                                                 
'use strict';
var chokidar = require('chokidar');
var eslint = require('eslint');
var chalk = require('chalk');
var _ = require('lodash');
var path = require('path');
 
var success = require('./formatters/helpers/success');
var formatter = require('./formatters/simple-detail');
var logger = require('./log')('watcher');
logger.debug('Loaded');
 
var events = {
  change: 'change'
};
var chokidarOptions = {
  ignored: /\.git|node_modules|bower_components/
};
 
var cli = new eslint.CLIEngine();
 
function successMessage(result) {
  logger.debug('result: %o', result);
  Eif (!result.errorCount && !result.warningCount) {
    return success(result) + chalk.grey(' (' + new Date().toLocaleTimeString() + ')');
  }
  return '';
}
 
function lintFile(path, config) {
  logger.debug('lintFile: %s', path);
  var results = cli.executeOnFiles([path], config).results;
  logger.log(successMessage(results[0]));
  logger.log(formatter(results));
}
 
function isWatchableExtension(filePath){
  return _.contains(cli.options.extensions, path.extname(filePath));
}
 
module.exports = function watcher(options) {
  chokidar.watch(options._, chokidarOptions)
    .on(events.change, function (path) {
      logger.debug('Changed:', path);
      if(!cli.isPathIgnored(path) && isWatchableExtension(path)){
        var config = cli.getConfigForFile(path);
        lintFile(path, config);
      }
    }).on('error', function(err){
      logger.log(err);
    });
 
  logger.debug('Watching: %o', options._);
};