You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.4 KiB

  1. /*
  2. ** © 2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller
  3. ** Licensed under MIT License.
  4. */
  5. /* jshint node:true */
  6. "use strict";
  7. if (process.platform !== "darwin") {
  8. throw new Error(`Module 'fsevents' is not compatible with platform '${process.platform}'`);
  9. }
  10. const Native = require("./fsevents.node");
  11. const events = Native.constants;
  12. function watch(path, since, handler) {
  13. if (typeof path !== "string") {
  14. throw new TypeError(`fsevents argument 1 must be a string and not a ${typeof path}`);
  15. }
  16. if ("function" === typeof since && "undefined" === typeof handler) {
  17. handler = since;
  18. since = Native.flags.SinceNow;
  19. }
  20. if (typeof since !== "number") {
  21. throw new TypeError(`fsevents argument 2 must be a number and not a ${typeof since}`);
  22. }
  23. if (typeof handler !== "function") {
  24. throw new TypeError(`fsevents argument 3 must be a function and not a ${typeof handler}`);
  25. }
  26. let instance = Native.start(Native.global, path, since, handler);
  27. if (!instance) throw new Error(`could not watch: ${path}`);
  28. return () => {
  29. const result = instance ? Promise.resolve(instance).then(Native.stop) : Promise.resolve(undefined);
  30. instance = undefined;
  31. return result;
  32. };
  33. }
  34. function getInfo(path, flags) {
  35. return {
  36. path,
  37. flags,
  38. event: getEventType(flags),
  39. type: getFileType(flags),
  40. changes: getFileChanges(flags),
  41. };
  42. }
  43. function getFileType(flags) {
  44. if (events.ItemIsFile & flags) return "file";
  45. if (events.ItemIsDir & flags) return "directory";
  46. if (events.MustScanSubDirs & flags) return "directory";
  47. if (events.ItemIsSymlink & flags) return "symlink";
  48. }
  49. function anyIsTrue(obj) {
  50. for (let key in obj) {
  51. if (obj[key]) return true;
  52. }
  53. return false;
  54. }
  55. function getEventType(flags) {
  56. if (events.ItemRemoved & flags) return "deleted";
  57. if (events.ItemRenamed & flags) return "moved";
  58. if (events.ItemCreated & flags) return "created";
  59. if (events.ItemModified & flags) return "modified";
  60. if (events.RootChanged & flags) return "root-changed";
  61. if (events.ItemCloned & flags) return "cloned";
  62. if (anyIsTrue(flags)) return "modified";
  63. return "unknown";
  64. }
  65. function getFileChanges(flags) {
  66. return {
  67. inode: !!(events.ItemInodeMetaMod & flags),
  68. finder: !!(events.ItemFinderInfoMod & flags),
  69. access: !!(events.ItemChangeOwner & flags),
  70. xattrs: !!(events.ItemXattrMod & flags),
  71. };
  72. }
  73. exports.watch = watch;
  74. exports.getInfo = getInfo;
  75. exports.constants = events;