cli.js 1.63 KB
Newer Older
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
#!/usr/bin/env node
'use strict';

const sane = require('../');
const argv = require('minimist')(process.argv.slice(2));
const execshell = require('exec-sh');

if (argv._.length === 0) {
  const msg =
    'Usage: sane <command> [...directory] [--glob=<filePattern>] ' +
    '[--ignored=<filePattern>] [--poll] [--watchman] [--watchman-path=<watchmanBinaryPath>] [--dot] ' +
    '[--wait=<seconds>] [--only-changes] [--quiet]';
  console.error(msg);
  process.exit();
}

const opts = {};
const command = argv._[0];
const dir = argv._[1] || process.cwd();
const waitTime = Number(argv.wait || argv.w);
const dot = argv.dot || argv.d;
const glob = argv.glob || argv.g;
const ignored = argv.ignored || argv.i;
const poll = argv.poll || argv.p;
const watchman = argv.watchman || argv.w;
const watchmanPath = argv['watchman-path'];
const onlyChanges = argv['only-changes'] | argv.o;
const quiet = argv.quiet | argv.q;

if (dot) {
  opts.dot = true;
}
if (glob) {
  opts.glob = glob;
}
if (ignored) {
  opts.ignored = ignored;
}
if (poll) {
  opts.poll = true;
}
if (watchman) {
  opts.watchman = true;
}
if (watchmanPath) {
  opts.watchmanPath = watchmanPath;
}

let wait = false;
const watcher = sane(dir, opts);

watcher.on('ready', function() {
  if (!quiet) {
    console.log('Watching: ', dir + '/' + (opts.glob || ''));
  }
  if (!onlyChanges) {
    execshell(command);
  }
});

watcher.on('change', function(filepath) {
  if (wait) {
    return;
  }
  if (!quiet) {
    console.log('Change detected in:', filepath);
  }
  execshell(command);

  if (waitTime > 0) {
    wait = true;
    setTimeout(function() {
      wait = false;
    }, waitTime * 1000);
  }
});