@eduardo191labs/watcher 0.0.0-stage → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CMakeLists.txt +82 -0
  2. package/LICENSE +21 -0
  3. package/README.md +135 -2
  4. package/binding.gyp +125 -0
  5. package/index.d.ts +49 -0
  6. package/index.js +55 -0
  7. package/index.js.flow +45 -0
  8. package/package.json +61 -3
  9. package/scripts/build-from-source.js +16 -0
  10. package/src/Backend.cc +186 -0
  11. package/src/Backend.hh +37 -0
  12. package/src/Debounce.cc +113 -0
  13. package/src/Debounce.hh +49 -0
  14. package/src/DirTree.cc +164 -0
  15. package/src/DirTree.hh +50 -0
  16. package/src/Event.hh +109 -0
  17. package/src/Glob.cc +22 -0
  18. package/src/Glob.hh +34 -0
  19. package/src/PromiseRunner.hh +101 -0
  20. package/src/Signal.hh +46 -0
  21. package/src/Watcher.cc +241 -0
  22. package/src/Watcher.hh +73 -0
  23. package/src/binding.cc +268 -0
  24. package/src/kqueue/KqueueBackend.cc +306 -0
  25. package/src/kqueue/KqueueBackend.hh +35 -0
  26. package/src/linux/InotifyBackend.cc +236 -0
  27. package/src/linux/InotifyBackend.hh +34 -0
  28. package/src/macos/FSEventsBackend.cc +338 -0
  29. package/src/macos/FSEventsBackend.hh +20 -0
  30. package/src/shared/BruteForceBackend.cc +41 -0
  31. package/src/shared/BruteForceBackend.hh +25 -0
  32. package/src/unix/fts.cc +50 -0
  33. package/src/unix/legacy.cc +77 -0
  34. package/src/wasm/WasmBackend.cc +132 -0
  35. package/src/wasm/WasmBackend.hh +34 -0
  36. package/src/wasm/include.h +74 -0
  37. package/src/watchman/BSER.cc +302 -0
  38. package/src/watchman/BSER.hh +69 -0
  39. package/src/watchman/IPC.hh +175 -0
  40. package/src/watchman/WatchmanBackend.cc +342 -0
  41. package/src/watchman/WatchmanBackend.hh +35 -0
  42. package/src/windows/WindowsBackend.cc +282 -0
  43. package/src/windows/WindowsBackend.hh +18 -0
  44. package/src/windows/win_utils.cc +44 -0
  45. package/src/windows/win_utils.hh +11 -0
  46. package/wrapper.js +88 -0
@@ -0,0 +1,236 @@
1
+ #include <memory>
2
+ #include <poll.h>
3
+ #include <unistd.h>
4
+ #include <fcntl.h>
5
+ #include <sys/stat.h>
6
+ #include "InotifyBackend.hh"
7
+
8
+ #define INOTIFY_MASK \
9
+ IN_ATTRIB | IN_CREATE | IN_DELETE | \
10
+ IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | \
11
+ IN_MOVED_TO | IN_DONT_FOLLOW | IN_ONLYDIR | IN_EXCL_UNLINK
12
+ #define BUFFER_SIZE 8192
13
+ #define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec)
14
+
15
+ void InotifyBackend::start() {
16
+ // Create a pipe that we will write to when we want to end the thread.
17
+ int err = pipe2(mPipe, O_CLOEXEC | O_NONBLOCK);
18
+ if (err == -1) {
19
+ throw std::runtime_error(std::string("Unable to open pipe: ") + strerror(errno));
20
+ }
21
+
22
+ // Init inotify file descriptor.
23
+ mInotify = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
24
+ if (mInotify == -1) {
25
+ throw std::runtime_error(std::string("Unable to initialize inotify: ") + strerror(errno));
26
+ }
27
+
28
+ pollfd pollfds[2];
29
+ pollfds[0].fd = mPipe[0];
30
+ pollfds[0].events = POLLIN;
31
+ pollfds[0].revents = 0;
32
+ pollfds[1].fd = mInotify;
33
+ pollfds[1].events = POLLIN;
34
+ pollfds[1].revents = 0;
35
+
36
+ notifyStarted();
37
+
38
+ // Loop until we get an event from the pipe.
39
+ while (true) {
40
+ int result = poll(pollfds, 2, 500);
41
+ if (result < 0) {
42
+ throw std::runtime_error(std::string("Unable to poll: ") + strerror(errno));
43
+ }
44
+
45
+ if (pollfds[0].revents) {
46
+ break;
47
+ }
48
+
49
+ if (pollfds[1].revents) {
50
+ handleEvents();
51
+ }
52
+ }
53
+
54
+ close(mPipe[0]);
55
+ close(mPipe[1]);
56
+ close(mInotify);
57
+
58
+ mEndedSignal.notify();
59
+ }
60
+
61
+ InotifyBackend::~InotifyBackend() {
62
+ write(mPipe[1], "X", 1);
63
+ mEndedSignal.wait();
64
+ }
65
+
66
+ // This function is called by Backend::watch which takes a lock on mMutex
67
+ void InotifyBackend::subscribe(WatcherRef watcher) {
68
+ // Build a full directory tree recursively, and watch each directory.
69
+ std::shared_ptr<DirTree> tree = getTree(watcher);
70
+
71
+ for (auto it = tree->entries.begin(); it != tree->entries.end(); it++) {
72
+ if (it->second.isDir) {
73
+ bool success = watchDir(watcher, it->second.path, tree);
74
+ if (!success) {
75
+ throw WatcherError(std::string("inotify_add_watch on '") + it->second.path + std::string("' failed: ") + strerror(errno), watcher);
76
+ }
77
+ }
78
+ }
79
+ }
80
+
81
+ bool InotifyBackend::watchDir(WatcherRef watcher, std::string path, std::shared_ptr<DirTree> tree) {
82
+ int wd = inotify_add_watch(mInotify, path.c_str(), INOTIFY_MASK);
83
+ if (wd == -1) {
84
+ return false;
85
+ }
86
+
87
+ std::shared_ptr<InotifySubscription> sub = std::make_shared<InotifySubscription>();
88
+ sub->tree = tree;
89
+ sub->path = path;
90
+ sub->watcher = watcher;
91
+ mSubscriptions.emplace(wd, sub);
92
+
93
+ return true;
94
+ }
95
+
96
+ void InotifyBackend::handleEvents() {
97
+ char buf[BUFFER_SIZE] __attribute__ ((aligned(__alignof__(struct inotify_event))));;
98
+ struct inotify_event *event;
99
+
100
+ // Track all of the watchers that are touched so we can notify them at the end of the events.
101
+ std::unordered_set<WatcherRef> watchers;
102
+
103
+ while (true) {
104
+ int n = read(mInotify, &buf, BUFFER_SIZE);
105
+ if (n < 0) {
106
+ if (errno == EAGAIN || errno == EWOULDBLOCK) {
107
+ break;
108
+ }
109
+
110
+ throw std::runtime_error(std::string("Error reading from inotify: ") + strerror(errno));
111
+ }
112
+
113
+ if (n == 0) {
114
+ break;
115
+ }
116
+
117
+ for (char *ptr = buf; ptr < buf + n; ptr += sizeof(*event) + event->len) {
118
+ event = (struct inotify_event *)ptr;
119
+
120
+ if ((event->mask & IN_Q_OVERFLOW) == IN_Q_OVERFLOW) {
121
+ // overflow
122
+ continue;
123
+ }
124
+
125
+ handleEvent(event, watchers);
126
+ }
127
+ }
128
+
129
+ for (auto it = watchers.begin(); it != watchers.end(); it++) {
130
+ (*it)->notify();
131
+ }
132
+ }
133
+
134
+ void InotifyBackend::handleEvent(struct inotify_event *event, std::unordered_set<WatcherRef> &watchers) {
135
+ std::unique_lock<std::mutex> lock(mMutex);
136
+
137
+ // Find the subscriptions for this watch descriptor
138
+ auto range = mSubscriptions.equal_range(event->wd);
139
+ std::unordered_set<std::shared_ptr<InotifySubscription>> set;
140
+ for (auto it = range.first; it != range.second; it++) {
141
+ set.insert(it->second);
142
+ }
143
+
144
+ for (auto it = set.begin(); it != set.end(); it++) {
145
+ if (handleSubscription(event, *it)) {
146
+ watchers.insert((*it)->watcher);
147
+ }
148
+ }
149
+ }
150
+
151
+ bool InotifyBackend::handleSubscription(struct inotify_event *event, std::shared_ptr<InotifySubscription> sub) {
152
+ // Build full path and check if its in our ignore list.
153
+ std::shared_ptr<Watcher> watcher = sub->watcher;
154
+ std::string path = std::string(sub->path);
155
+ bool isDir = event->mask & IN_ISDIR;
156
+
157
+ if (event->len > 0) {
158
+ path += "/" + std::string(event->name);
159
+ }
160
+
161
+ if (watcher->isIgnored(path)) {
162
+ return false;
163
+ }
164
+
165
+ // If this is a create, check if it's a directory and start watching if it is.
166
+ // In any case, keep the directory tree up to date.
167
+ if (event->mask & (IN_CREATE | IN_MOVED_TO)) {
168
+ watcher->mEvents.create(path);
169
+
170
+ struct stat st;
171
+ // Use lstat to avoid resolving symbolic links that we cannot watch anyway
172
+ // https://github.com/parcel-bundler/watcher/issues/76
173
+ if (lstat(path.c_str(), &st) != 0) {
174
+ return false;
175
+ }
176
+ DirEntry *entry = sub->tree->add(path, CONVERT_TIME(st.st_mtim), S_ISDIR(st.st_mode));
177
+
178
+ if (entry->isDir) {
179
+ bool success = watchDir(watcher, path, sub->tree);
180
+ if (!success) {
181
+ sub->tree->remove(path);
182
+ return false;
183
+ }
184
+ }
185
+ } else if (event->mask & (IN_MODIFY | IN_ATTRIB)) {
186
+ watcher->mEvents.update(path);
187
+
188
+ struct stat st;
189
+ if (stat(path.c_str(), &st) != 0) {
190
+ return false;
191
+ }
192
+ sub->tree->update(path, CONVERT_TIME(st.st_mtim));
193
+ } else if (event->mask & (IN_DELETE | IN_DELETE_SELF | IN_MOVED_FROM | IN_MOVE_SELF)) {
194
+ bool isSelfEvent = (event->mask & (IN_DELETE_SELF | IN_MOVE_SELF));
195
+ // Ignore delete/move self events unless this is the recursive watch root
196
+ if (isSelfEvent && path != watcher->mDir) {
197
+ return false;
198
+ }
199
+
200
+ // If the entry being deleted/moved is a directory, remove it from the list of subscriptions
201
+ // XXX: self events don't have the IN_ISDIR mask
202
+ if (isSelfEvent || isDir) {
203
+ for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) {
204
+ if (it->second->path == path) {
205
+ it = mSubscriptions.erase(it);
206
+ } else {
207
+ ++it;
208
+ }
209
+ }
210
+ }
211
+
212
+ watcher->mEvents.remove(path);
213
+ sub->tree->remove(path);
214
+ }
215
+
216
+ return true;
217
+ }
218
+
219
+ // This function is called by Backend::unwatch which takes a lock on mMutex
220
+ void InotifyBackend::unsubscribe(WatcherRef watcher) {
221
+ // Find any subscriptions pointing to this watcher, and remove them.
222
+ for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) {
223
+ if (it->second->watcher.get() == watcher.get()) {
224
+ if (mSubscriptions.count(it->first) == 1) {
225
+ int err = inotify_rm_watch(mInotify, it->first);
226
+ if (err == -1) {
227
+ throw WatcherError(std::string("Unable to remove watcher: ") + strerror(errno), watcher);
228
+ }
229
+ }
230
+
231
+ it = mSubscriptions.erase(it);
232
+ } else {
233
+ it++;
234
+ }
235
+ }
236
+ }
@@ -0,0 +1,34 @@
1
+ #ifndef INOTIFY_H
2
+ #define INOTIFY_H
3
+
4
+ #include <unordered_map>
5
+ #include <sys/inotify.h>
6
+ #include "../shared/BruteForceBackend.hh"
7
+ #include "../DirTree.hh"
8
+ #include "../Signal.hh"
9
+
10
+ struct InotifySubscription {
11
+ std::shared_ptr<DirTree> tree;
12
+ std::string path;
13
+ WatcherRef watcher;
14
+ };
15
+
16
+ class InotifyBackend : public BruteForceBackend {
17
+ public:
18
+ void start() override;
19
+ ~InotifyBackend();
20
+ void subscribe(WatcherRef watcher) override;
21
+ void unsubscribe(WatcherRef watcher) override;
22
+ private:
23
+ int mPipe[2];
24
+ int mInotify;
25
+ std::unordered_multimap<int, std::shared_ptr<InotifySubscription>> mSubscriptions;
26
+ Signal mEndedSignal;
27
+
28
+ bool watchDir(WatcherRef watcher, std::string path, std::shared_ptr<DirTree> tree);
29
+ void handleEvents();
30
+ void handleEvent(struct inotify_event *event, std::unordered_set<WatcherRef> &watchers);
31
+ bool handleSubscription(struct inotify_event *event, std::shared_ptr<InotifySubscription> sub);
32
+ };
33
+
34
+ #endif
@@ -0,0 +1,338 @@
1
+ #include <CoreServices/CoreServices.h>
2
+ #include <sys/stat.h>
3
+ #include <string>
4
+ #include <fstream>
5
+ #include <unordered_set>
6
+ #include "../Event.hh"
7
+ #include "../Backend.hh"
8
+ #include "./FSEventsBackend.hh"
9
+ #include "../Watcher.hh"
10
+
11
+ #define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec)
12
+ #define IGNORED_FLAGS (kFSEventStreamEventFlagItemIsHardlink | kFSEventStreamEventFlagItemIsLastHardlink | kFSEventStreamEventFlagItemIsSymlink | kFSEventStreamEventFlagItemIsDir | kFSEventStreamEventFlagItemIsFile)
13
+
14
+ void stopStream(FSEventStreamRef stream, CFRunLoopRef runLoop) {
15
+ FSEventStreamStop(stream);
16
+ FSEventStreamUnscheduleFromRunLoop(stream, runLoop, kCFRunLoopDefaultMode);
17
+ FSEventStreamInvalidate(stream);
18
+ FSEventStreamRelease(stream);
19
+ }
20
+
21
+ // macOS has a case insensitive file system by default. In order to detect
22
+ // file renames that only affect case, we need to get the canonical path
23
+ // and compare it with the input path to determine if a file was created or deleted.
24
+ bool pathExists(char *path) {
25
+ int fd = open(path, O_RDONLY | O_SYMLINK);
26
+ if (fd == -1) {
27
+ return false;
28
+ }
29
+
30
+ char buf[PATH_MAX];
31
+ if (fcntl(fd, F_GETPATH, buf) == -1) {
32
+ close(fd);
33
+ return false;
34
+ }
35
+
36
+ bool res = strncmp(path, buf, PATH_MAX) == 0;
37
+ close(fd);
38
+ return res;
39
+ }
40
+
41
+ class State: public WatcherState {
42
+ public:
43
+ FSEventStreamRef stream;
44
+ std::shared_ptr<DirTree> tree;
45
+ uint64_t since;
46
+ };
47
+
48
+ void FSEventsCallback(
49
+ ConstFSEventStreamRef streamRef,
50
+ void *clientCallBackInfo,
51
+ size_t numEvents,
52
+ void *eventPaths,
53
+ const FSEventStreamEventFlags eventFlags[],
54
+ const FSEventStreamEventId eventIds[]
55
+ ) {
56
+ char **paths = (char **)eventPaths;
57
+ std::shared_ptr<Watcher>& watcher = *static_cast<std::shared_ptr<Watcher> *>(clientCallBackInfo);
58
+
59
+ EventList& list = watcher->mEvents;
60
+ if (watcher->state == nullptr) {
61
+ return;
62
+ }
63
+
64
+ auto stateGuard = watcher->state;
65
+ auto* state = static_cast<State*>(stateGuard.get());
66
+ uint64_t since = state->since;
67
+ bool deletedRoot = false;
68
+
69
+ for (size_t i = 0; i < numEvents; ++i) {
70
+ bool isCreated = (eventFlags[i] & kFSEventStreamEventFlagItemCreated) == kFSEventStreamEventFlagItemCreated;
71
+ bool isRemoved = (eventFlags[i] & kFSEventStreamEventFlagItemRemoved) == kFSEventStreamEventFlagItemRemoved;
72
+ bool isModified = (eventFlags[i] & kFSEventStreamEventFlagItemModified) == kFSEventStreamEventFlagItemModified ||
73
+ (eventFlags[i] & kFSEventStreamEventFlagItemInodeMetaMod) == kFSEventStreamEventFlagItemInodeMetaMod ||
74
+ (eventFlags[i] & kFSEventStreamEventFlagItemFinderInfoMod) == kFSEventStreamEventFlagItemFinderInfoMod ||
75
+ (eventFlags[i] & kFSEventStreamEventFlagItemChangeOwner) == kFSEventStreamEventFlagItemChangeOwner ||
76
+ (eventFlags[i] & kFSEventStreamEventFlagItemXattrMod) == kFSEventStreamEventFlagItemXattrMod;
77
+ bool isRenamed = (eventFlags[i] & kFSEventStreamEventFlagItemRenamed) == kFSEventStreamEventFlagItemRenamed;
78
+ bool isDone = (eventFlags[i] & kFSEventStreamEventFlagHistoryDone) == kFSEventStreamEventFlagHistoryDone;
79
+ bool isDir = (eventFlags[i] & kFSEventStreamEventFlagItemIsDir) == kFSEventStreamEventFlagItemIsDir;
80
+
81
+
82
+ if (eventFlags[i] & kFSEventStreamEventFlagMustScanSubDirs) {
83
+ if (eventFlags[i] & kFSEventStreamEventFlagUserDropped) {
84
+ list.error("Events were dropped by the FSEvents client. File system must be re-scanned.");
85
+ } else if (eventFlags[i] & kFSEventStreamEventFlagKernelDropped) {
86
+ list.error("Events were dropped by the kernel. File system must be re-scanned.");
87
+ } else {
88
+ list.error("Too many events. File system must be re-scanned.");
89
+ }
90
+ }
91
+
92
+ if (isDone) {
93
+ watcher->notify();
94
+ break;
95
+ }
96
+
97
+ auto ignoredFlags = IGNORED_FLAGS;
98
+ if (__builtin_available(macOS 10.13, *)) {
99
+ ignoredFlags |= kFSEventStreamEventFlagItemCloned;
100
+ }
101
+
102
+ // If we don't care about any of the flags that are set, ignore this event.
103
+ if ((eventFlags[i] & ~ignoredFlags) == 0) {
104
+ continue;
105
+ }
106
+
107
+ // FSEvents exclusion paths only apply to files, not directories.
108
+ if (watcher->isIgnored(paths[i])) {
109
+ continue;
110
+ }
111
+
112
+ // Handle unambiguous events first
113
+ if (isCreated && !(isRemoved || isModified || isRenamed)) {
114
+ state->tree->add(paths[i], 0, isDir);
115
+ list.create(paths[i]);
116
+ } else if (isRemoved && !(isCreated || isModified || isRenamed)) {
117
+ state->tree->remove(paths[i]);
118
+ list.remove(paths[i]);
119
+ if (paths[i] == watcher->mDir) {
120
+ deletedRoot = true;
121
+ }
122
+ } else if (isModified && !(isCreated || isRemoved || isRenamed)) {
123
+ struct stat file;
124
+ if (stat(paths[i], &file)) {
125
+ continue;
126
+ }
127
+
128
+ // Ignore if mtime is the same as the last event.
129
+ // This prevents duplicate events from being emitted.
130
+ // If tv_nsec is zero, the file system probably only has second-level
131
+ // granularity so allow the even through in that case.
132
+ uint64_t mtime = CONVERT_TIME(file.st_mtimespec);
133
+ DirEntry *entry = state->tree->find(paths[i]);
134
+ if (entry && mtime == entry->mtime && file.st_mtimespec.tv_nsec != 0) {
135
+ continue;
136
+ }
137
+
138
+ if (entry) {
139
+ // Update mtime.
140
+ entry->mtime = mtime;
141
+ } else {
142
+ // Add to tree if this path has not been discovered yet.
143
+ state->tree->add(paths[i], mtime, S_ISDIR(file.st_mode));
144
+ }
145
+
146
+ list.update(paths[i]);
147
+ } else {
148
+ // If multiple flags were set, then we need to call `stat` to determine if the file really exists.
149
+ // This helps disambiguate creates, updates, and deletes.
150
+ struct stat file;
151
+ if (stat(paths[i], &file) || !pathExists(paths[i])) {
152
+ // File does not exist, so we have to assume it was removed. This is not exact since the
153
+ // flags set by fsevents get coalesced together (e.g. created & deleted), so there is no way to
154
+ // know whether the create and delete both happened since our snapshot (in which case
155
+ // we'd rather ignore this event completely). This will result in some extra delete events
156
+ // being emitted for files we don't know about, but that is the best we can do.
157
+ state->tree->remove(paths[i]);
158
+ list.remove(paths[i]);
159
+ if (paths[i] == watcher->mDir) {
160
+ deletedRoot = true;
161
+ }
162
+ continue;
163
+ }
164
+
165
+ // If the file was modified, and existed before, then this is an update, otherwise a create.
166
+ uint64_t ctime = CONVERT_TIME(file.st_birthtimespec);
167
+ uint64_t mtime = CONVERT_TIME(file.st_mtimespec);
168
+ DirEntry *entry = !since ? state->tree->find(paths[i]) : NULL;
169
+ if (entry && entry->mtime == mtime && file.st_mtimespec.tv_nsec != 0) {
170
+ continue;
171
+ }
172
+
173
+ // Some mounted file systems report a creation time of 0/unix epoch which we special case.
174
+ if (isModified && (entry || (ctime <= since && ctime != 0))) {
175
+ state->tree->update(paths[i], mtime);
176
+ list.update(paths[i]);
177
+ } else {
178
+ state->tree->add(paths[i], mtime, S_ISDIR(file.st_mode));
179
+ list.create(paths[i]);
180
+ }
181
+ }
182
+ }
183
+
184
+ if (!since) {
185
+ watcher->notify();
186
+ }
187
+
188
+ // Stop watching if the root directory was deleted.
189
+ if (deletedRoot) {
190
+ stopStream((FSEventStreamRef)streamRef, CFRunLoopGetCurrent());
191
+ watcher->state = nullptr;
192
+ }
193
+ }
194
+
195
+ void checkWatcher(WatcherRef watcher) {
196
+ struct stat file;
197
+ if (stat(watcher->mDir.c_str(), &file)) {
198
+ throw WatcherError(strerror(errno), watcher);
199
+ }
200
+
201
+ if (!S_ISDIR(file.st_mode)) {
202
+ throw WatcherError(strerror(ENOTDIR), watcher);
203
+ }
204
+ }
205
+
206
+ void FSEventsBackend::startStream(WatcherRef watcher, FSEventStreamEventId id) {
207
+ checkWatcher(watcher);
208
+
209
+ CFAbsoluteTime latency = 0.001;
210
+ CFStringRef fileWatchPath = CFStringCreateWithCString(
211
+ NULL,
212
+ watcher->mDir.c_str(),
213
+ kCFStringEncodingUTF8
214
+ );
215
+
216
+ CFArrayRef pathsToWatch = CFArrayCreate(
217
+ NULL,
218
+ (const void **)&fileWatchPath,
219
+ 1,
220
+ NULL
221
+ );
222
+
223
+ // Make a watcher reference we can pass into the callback. This ensures bumped ref-count.
224
+ std::shared_ptr<Watcher>* callbackWatcher = new std::shared_ptr<Watcher> (watcher);
225
+ FSEventStreamContext callbackInfo {0, static_cast<void*> (callbackWatcher), nullptr, nullptr, nullptr};
226
+ FSEventStreamRef stream = FSEventStreamCreate(
227
+ NULL,
228
+ &FSEventsCallback,
229
+ &callbackInfo,
230
+ pathsToWatch,
231
+ id,
232
+ latency,
233
+ kFSEventStreamCreateFlagFileEvents
234
+ );
235
+
236
+ CFMutableArrayRef exclusions = CFArrayCreateMutable(NULL, watcher->mIgnorePaths.size(), NULL);
237
+ for (auto it = watcher->mIgnorePaths.begin(); it != watcher->mIgnorePaths.end(); it++) {
238
+ CFStringRef path = CFStringCreateWithCString(
239
+ NULL,
240
+ it->c_str(),
241
+ kCFStringEncodingUTF8
242
+ );
243
+
244
+ CFArrayAppendValue(exclusions, (const void *)path);
245
+ }
246
+
247
+ FSEventStreamSetExclusionPaths(stream, exclusions);
248
+
249
+ FSEventStreamScheduleWithRunLoop(stream, mRunLoop, kCFRunLoopDefaultMode);
250
+ bool started = FSEventStreamStart(stream);
251
+
252
+ CFRelease(pathsToWatch);
253
+ CFRelease(fileWatchPath);
254
+
255
+ if (!started) {
256
+ FSEventStreamRelease(stream);
257
+ throw WatcherError("Error starting FSEvents stream", watcher);
258
+ }
259
+
260
+ auto stateGuard = watcher->state;
261
+ State* s = static_cast<State*>(stateGuard.get());
262
+ s->tree = std::make_shared<DirTree>(watcher->mDir);
263
+ s->stream = stream;
264
+ }
265
+
266
+ void FSEventsBackend::start() {
267
+ mRunLoop = CFRunLoopGetCurrent();
268
+ CFRetain(mRunLoop);
269
+
270
+ // Unlock once run loop has started.
271
+ CFRunLoopPerformBlock(mRunLoop, kCFRunLoopDefaultMode, ^ {
272
+ notifyStarted();
273
+ });
274
+
275
+ CFRunLoopWakeUp(mRunLoop);
276
+ CFRunLoopRun();
277
+ }
278
+
279
+ FSEventsBackend::~FSEventsBackend() {
280
+ std::unique_lock<std::mutex> lock(mMutex);
281
+ CFRunLoopStop(mRunLoop);
282
+ CFRelease(mRunLoop);
283
+ }
284
+
285
+ void FSEventsBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) {
286
+ std::unique_lock<std::mutex> lock(mMutex);
287
+ checkWatcher(watcher);
288
+
289
+ FSEventStreamEventId id = FSEventsGetCurrentEventId();
290
+ std::ofstream ofs(*snapshotPath);
291
+ ofs << id;
292
+ ofs << "\n";
293
+
294
+ struct timespec now;
295
+ clock_gettime(CLOCK_REALTIME, &now);
296
+ ofs << CONVERT_TIME(now);
297
+ }
298
+
299
+ void FSEventsBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) {
300
+ std::unique_lock<std::mutex> lock(mMutex);
301
+ std::ifstream ifs(*snapshotPath);
302
+ if (ifs.fail()) {
303
+ return;
304
+ }
305
+
306
+ FSEventStreamEventId id;
307
+ uint64_t since;
308
+ ifs >> id;
309
+ ifs >> since;
310
+
311
+ auto s = std::make_shared<State>();
312
+ s->since = since;
313
+ watcher->state = s;
314
+
315
+ startStream(watcher, id);
316
+ watcher->wait();
317
+ stopStream(s->stream, mRunLoop);
318
+
319
+ watcher->state = nullptr;
320
+ }
321
+
322
+ // This function is called by Backend::watch which takes a lock on mMutex
323
+ void FSEventsBackend::subscribe(WatcherRef watcher) {
324
+ auto s = std::make_shared<State>();
325
+ s->since = 0;
326
+ watcher->state = s;
327
+ startStream(watcher, kFSEventStreamEventIdSinceNow);
328
+ }
329
+
330
+ // This function is called by Backend::unwatch which takes a lock on mMutex
331
+ void FSEventsBackend::unsubscribe(WatcherRef watcher) {
332
+ auto stateGuard = watcher->state;
333
+ State* s = static_cast<State*>(stateGuard.get());
334
+ if (s != nullptr) {
335
+ stopStream(s->stream, mRunLoop);
336
+ watcher->state = nullptr;
337
+ }
338
+ }
@@ -0,0 +1,20 @@
1
+ #ifndef FS_EVENTS_H
2
+ #define FS_EVENTS_H
3
+
4
+ #include <CoreServices/CoreServices.h>
5
+ #include "../Backend.hh"
6
+
7
+ class FSEventsBackend : public Backend {
8
+ public:
9
+ void start() override;
10
+ ~FSEventsBackend();
11
+ void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) override;
12
+ void getEventsSince(WatcherRef watcher, std::string *snapshotPath) override;
13
+ void subscribe(WatcherRef watcher) override;
14
+ void unsubscribe(WatcherRef watcher) override;
15
+ private:
16
+ void startStream(WatcherRef watcher, FSEventStreamEventId id);
17
+ CFRunLoopRef mRunLoop;
18
+ };
19
+
20
+ #endif
@@ -0,0 +1,41 @@
1
+ #include <string>
2
+ #include "../DirTree.hh"
3
+ #include "../Event.hh"
4
+ #include "./BruteForceBackend.hh"
5
+
6
+ std::shared_ptr<DirTree> BruteForceBackend::getTree(WatcherRef watcher, bool shouldRead) {
7
+ auto tree = DirTree::getCached(watcher->mDir);
8
+
9
+ // If the tree is not complete, read it if needed.
10
+ if (!tree->isComplete && shouldRead) {
11
+ readTree(watcher, tree);
12
+ tree->isComplete = true;
13
+ }
14
+
15
+ return tree;
16
+ }
17
+
18
+ void BruteForceBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) {
19
+ std::unique_lock<std::mutex> lock(mMutex);
20
+ auto tree = getTree(watcher);
21
+ FILE *f = fopen(snapshotPath->c_str(), "w");
22
+ if (!f) {
23
+ throw std::runtime_error(std::string("Unable to open snapshot file: ") + strerror(errno));
24
+ }
25
+
26
+ tree->write(f);
27
+ fclose(f);
28
+ }
29
+
30
+ void BruteForceBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) {
31
+ std::unique_lock<std::mutex> lock(mMutex);
32
+ FILE *f = fopen(snapshotPath->c_str(), "r");
33
+ if (!f) {
34
+ throw std::runtime_error(std::string("Unable to open snapshot file: ") + strerror(errno));
35
+ }
36
+
37
+ DirTree snapshot{watcher->mDir, f};
38
+ auto now = getTree(watcher);
39
+ now->getChanges(&snapshot, watcher->mEvents);
40
+ fclose(f);
41
+ }
@@ -0,0 +1,25 @@
1
+ #ifndef BRUTE_FORCE_H
2
+ #define BRUTE_FORCE_H
3
+
4
+ #include "../Backend.hh"
5
+ #include "../DirTree.hh"
6
+ #include "../Watcher.hh"
7
+
8
+ class BruteForceBackend : public Backend {
9
+ public:
10
+ void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) override;
11
+ void getEventsSince(WatcherRef watcher, std::string *snapshotPath) override;
12
+ void subscribe(WatcherRef watcher) override {
13
+ throw "Brute force backend doesn't support subscriptions.";
14
+ }
15
+
16
+ void unsubscribe(WatcherRef watcher) override {
17
+ throw "Brute force backend doesn't support subscriptions.";
18
+ }
19
+
20
+ std::shared_ptr<DirTree> getTree(WatcherRef watcher, bool shouldRead = true);
21
+ private:
22
+ void readTree(WatcherRef watcher, std::shared_ptr<DirTree> tree);
23
+ };
24
+
25
+ #endif