cli.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env node
  2. var argv = require('minimist')(process.argv.slice(2))
  3. var execshell = require('exec-sh')
  4. var path = require('path')
  5. var watch = require('./main.js')
  6. if(argv._.length === 0) {
  7. console.error([
  8. 'Usage: watch <command> [...directory]',
  9. '[--wait=<seconds>]',
  10. '[--filter=<file>]',
  11. '[--interval=<seconds>]',
  12. '[--ignoreDotFiles]',
  13. '[--ignoreUnreadable]',
  14. '[--ignoreDirectoryPattern]'
  15. ].join(' '))
  16. process.exit()
  17. }
  18. var watchTreeOpts = {}
  19. var command = argv._[0]
  20. var dirs = []
  21. var i
  22. var argLen = argv._.length
  23. if (argLen > 1) {
  24. for(i = 1; i< argLen; i++) {
  25. dirs.push(argv._[i])
  26. }
  27. } else {
  28. dirs.push(process.cwd())
  29. }
  30. var waitTime = Number(argv.wait || argv.w)
  31. if (argv.interval || argv.i) {
  32. watchTreeOpts.interval = Number(argv.interval || argv.i || 0.2);
  33. }
  34. if(argv.ignoreDotFiles || argv.d)
  35. watchTreeOpts.ignoreDotFiles = true
  36. if(argv.ignoreUnreadable || argv.u)
  37. watchTreeOpts.ignoreUnreadableDir = true
  38. if(argv.ignoreDirectoryPattern || argv.p) {
  39. var match = (argv.ignoreDirectoryPattern || argv.p).match(/^\/(.*)\/([gimuy]*)$/);
  40. watchTreeOpts.ignoreDirectoryPattern = new RegExp(match[1], match[2])
  41. }
  42. if(argv.filter || argv.f) {
  43. try {
  44. watchTreeOpts.filter = require(path.resolve(process.cwd(), argv.filter || argv.f))
  45. } catch (e) {
  46. console.error(e)
  47. process.exit(1)
  48. }
  49. }
  50. var wait = false
  51. var dirLen = dirs.length
  52. var skip = dirLen - 1
  53. for(i = 0; i < dirLen; i++) {
  54. var dir = dirs[i]
  55. console.error('> Watching', dir)
  56. watch.watchTree(dir, watchTreeOpts, function (f, curr, prev) {
  57. if(skip) {
  58. skip--
  59. return
  60. }
  61. if(wait) return
  62. execshell(command)
  63. if(waitTime > 0) {
  64. wait = true
  65. setTimeout(function () {
  66. wait = false
  67. }, waitTime * 1000)
  68. }
  69. })
  70. }