all files / src/commands/ count.js

0% Statements 0/44
0% Branches 0/8
0% Functions 0/10
0% Lines 0/44
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105                                                                                                                                                                                                                 
import _ from 'lodash';
import yargs from 'yargs';
import common from './common-yargs';
import path from 'path';
import { countPath } from '../count';
import chalk from 'chalk';
import numberFormatter from 'format-number';
import columnify from 'columnify';
import { SELECTOR_LIMIT } from '../constants';
 
const formatNumber = numberFormatter();
 
function format(results, srcPath) {
  let formattedData = results
    .map(x => {
      let color = x.exceedsLimit ? chalk.red : chalk.green;
      let relativeFilepath = path.relative(srcPath, x.filepath);
      let formattedNumber = formatNumber(x.selectorCount);
 
      return {
        filepath: color(relativeFilepath),
        selectorCount: color(formattedNumber)
      };
    });
 
  let formattedResults = columnify(formattedData, {
    columnSplitter: '    ',
    config: {
      filepath: {
        headingTransform() { return chalk.bold.underline('File Path'); }
      },
      selectorCount: {
        headingTransform() { return chalk.bold.underline(`Selector Count (Limit: ${SELECTOR_LIMIT})`); }
      }
    }
  });
 
  return formattedResults;
}
 
function execute(options) {
  const srcPath = path.resolve(options.input);
 
  let countOptions = {
    progress(filepath) {
      process.stdout.write('.');
    }
  };
 
  return countPath(srcPath, countOptions)
    .then(results => {
      console.log('');
      let formattedResults = format(results, srcPath);
      console.log(formattedResults);
 
      if (_.some(results, 'exceedsLimit')){
        return 1;
      }
 
      return 0;
    });
}
 
function yargsSetup() {
  yargs.command('count', 'checks an existing css file and fails if the selector count exceeds IE limits');
}
 
function examples() {
  yargs.example('$0 count <file|directory>');
  yargs.example('$0 count <file|directory> --no-color');
}
 
function parseArgs(argv){
  yargs.reset();
 
  common();
  examples();
 
  let options = yargs
    .help('h')
    .alias('h', 'help')
    .option('c', {
      alias: 'color',
      default: true,
      description: 'Colored output',
      type: 'boolean'
    })
    .parse(argv);
 
  options.input = options._.length > 0 ? options._[0] : null;
 
  if (!options.input) {
    throw 'No input provided';
  }
 
  return options;
}
 
export default {
  execute,
  examples,
  yargsSetup,
  parseArgs
};