watcher.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. var grapher = require('sass-graph'),
  2. clonedeep = require('lodash/cloneDeep'),
  3. path = require('path'),
  4. config = {},
  5. watcher = {},
  6. graph = null;
  7. watcher.reset = function(opts) {
  8. config = clonedeep(opts || config || {});
  9. var options = {
  10. loadPaths: config.includePath,
  11. extensions: ['scss', 'sass', 'css'],
  12. follow: config.follow,
  13. };
  14. if (config.directory) {
  15. graph = grapher.parseDir(config.directory, options);
  16. } else {
  17. graph = grapher.parseFile(config.src, options);
  18. }
  19. return Object.keys(graph.index);
  20. };
  21. watcher.changed = function(absolutePath) {
  22. var files = {
  23. added: [],
  24. changed: [],
  25. removed: [],
  26. };
  27. this.reset();
  28. if (absolutePath && path.basename(absolutePath)[0] !== '_') {
  29. files.changed.push(absolutePath);
  30. }
  31. graph.visitAncestors(absolutePath, function(parent) {
  32. if (path.basename(parent)[0] !== '_') {
  33. files.changed.push(parent);
  34. }
  35. });
  36. graph.visitDescendents(absolutePath, function(child) {
  37. files.added.push(child);
  38. });
  39. return files;
  40. };
  41. watcher.added = function(absolutePath) {
  42. var files = {
  43. added: [],
  44. changed: [],
  45. removed: [],
  46. };
  47. this.reset();
  48. if (Object.keys(graph.index).indexOf(absolutePath) === -1) {
  49. files.added.push(absolutePath);
  50. }
  51. graph.visitDescendents(absolutePath, function(child) {
  52. files.added.push(child);
  53. });
  54. return files;
  55. };
  56. watcher.removed = function(absolutePath) {
  57. var files = {
  58. added: [],
  59. changed: [],
  60. removed: [],
  61. };
  62. graph.visitAncestors(absolutePath, function(parent) {
  63. if (path.basename(parent)[0] !== '_') {
  64. files.changed.push(parent);
  65. }
  66. });
  67. if (Object.keys(graph.index).indexOf(absolutePath) !== -1) {
  68. files.removed.push(absolutePath);
  69. }
  70. this.reset();
  71. return files;
  72. };
  73. module.exports = watcher;