forked from fsevents/fsevents
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fsevents.js
82 lines (74 loc) · 2.37 KB
/
fsevents.js
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
/*
** © 2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller
** Licensed under MIT License.
*/
/* jshint node:true */
"use strict";
if (process.platform !== "darwin") {
throw new Error(`Module 'fsevents' is not compatible with platform '${process.platform}'`);
}
const Native = require("./fsevents.node");
const events = Native.constants;
function watch(path, since, handler) {
if (typeof path !== "string") {
throw new TypeError(`fsevents argument 1 must be a string and not a ${typeof path}`);
}
if ("function" === typeof since && "undefined" === typeof handler) {
handler = since;
since = Native.flags.SinceNow;
}
if (typeof since !== "number") {
throw new TypeError(`fsevents argument 2 must be a number and not a ${typeof since}`);
}
if (typeof handler !== "function") {
throw new TypeError(`fsevents argument 3 must be a function and not a ${typeof handler}`);
}
let instance = Native.start(Native.global, path, since, handler);
if (!instance) throw new Error(`could not watch: ${path}`);
return () => {
const result = instance ? Promise.resolve(instance).then(Native.stop) : Promise.resolve(undefined);
instance = undefined;
return result;
};
}
function getInfo(path, flags) {
return {
path,
flags,
event: getEventType(flags),
type: getFileType(flags),
changes: getFileChanges(flags),
};
}
function getFileType(flags) {
if (events.ItemIsFile & flags) return "file";
if (events.ItemIsDir & flags) return "directory";
if (events.ItemIsSymlink & flags) return "symlink";
}
function anyIsTrue(obj) {
for (let key in obj) {
if (obj[key]) return true;
}
return false;
}
function getEventType(flags) {
if (events.ItemRemoved & flags) return "deleted";
if (events.ItemRenamed & flags) return "moved";
if (events.ItemCreated & flags) return "created";
if (events.ItemModified & flags) return "modified";
if (events.RootChanged & flags) return "root-changed";
if (events.ItemCloned & flags) return "cloned";
if (anyIsTrue(flags)) return "modified";
return "unknown";
}
function getFileChanges(flags) {
return {
inode: !!(events.ItemInodeMetaMod & flags),
finder: !!(events.ItemFinderInfoMod & flags),
access: !!(events.ItemChangeOwner & flags),
xattrs: !!(events.ItemXattrMod & flags),
};
}
exports.watch = watch;
exports.getInfo = getInfo;
exports.constants = events;