all files / src/ watcher.js

71.43% Statements 25/35
40% Branches 4/10
60% Functions 3/5
71.43% Lines 25/35
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                                                                             
'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/
};
 
function successMessage(result) {
  logger.debug('result: %o', result);
  if (!result.errorCount && !result.warningCount) {
    return success(result) + chalk.grey(' (' + new Date().toLocaleTimeString() + ')');
  }
  return '';
}
 
///https://github.com/eslint/eslint/blob/233440e524aa41545b66b2c3c7ca26fe790e32e0/tests/lib/cli-engine.js#L105-L107
 
module.exports = function watcher(options) {
  var cliOptions = {
    configFile: options.config
  };
  logger.debug(cliOptions);
  logger.debug(options);
  var cli = new eslint.CLIEngine(cliOptions);
 
  function lintFile(path) {
    logger.debug('lintFile: %s', path);
    var results = cli.executeOnFiles([path]).results;
    logger.log(successMessage(results[0]));
    logger.log(formatter(results));
  }
 
  function isWatchableExtension(filePath, extensions) {
    Iif (extensions) {
      return _.contains(extensions, path.extname(filePath));
    }
 
    // Use the ESLint default extension, if none is provided
    return _.contains(cli.options.extensions, path.extname(filePath));
  }
 
  chokidar.watch(options._, chokidarOptions)
    .on(events.change, function (path) {
      logger.debug('Changed:', path);
      Iif (!cli.isPathIgnored(path) && isWatchableExtension(path, options.ext)) {
        lintFile(path);
      }
    }).on('error', logger.error);
 
  logger.debug('Watching: %o', options._);
};