-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathFileWatcher.java
More file actions
245 lines (215 loc) · 7.38 KB
/
FileWatcher.java
File metadata and controls
245 lines (215 loc) · 7.38 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package org.javacomp.file;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import org.javacomp.logging.JLogger;
/**
* A wrapper around {@link WatchService} that supports watching both file system files and
* snapshotted files.
*/
class FileWatcher {
private static final JLogger logger = JLogger.createForEnclosingClass();
private final WatchService watchService;
private final Map<Path, WatchKey> watchKeyMap;
private final Set<Path> fileSnapshotPaths;
private final ExecutorService executor;
private final Path projectRoot;
private final ImmutableList<PathMatcher> ignorePathMatchers;
private Future<?> watchFuture = null;
private FileChangeListener listener = null;
FileWatcher(
Path projectRoot, ImmutableList<PathMatcher> ignorePathMatchers, ExecutorService executor) {
try {
this.watchService = FileSystems.getDefault().newWatchService();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.watchKeyMap = new HashMap<>();
this.fileSnapshotPaths = new HashSet<>();
this.executor = executor;
this.projectRoot = projectRoot;
this.ignorePathMatchers = ignorePathMatchers;
}
synchronized void setListener(FileChangeListener listener) {
this.listener = listener;
unsafeStartWatcher();
}
private void unsafeStartWatcher() {
if (watchFuture != null) {
return;
}
watchFuture = executor.submit(new WatchRunnable());
}
synchronized boolean watchDirectory(Path path) {
if (PathUtils.shouldIgnorePath(path, this.projectRoot, this.ignorePathMatchers)) {
logger.info("Ignore watching directory %s", path);
return false;
}
Path normalizedPath = path.normalize();
if (watchKeyMap.containsKey(normalizedPath)) {
logger.info("Directory %s has already been watched.", path);
return false;
}
try {
WatchKey watchKey =
path.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
watchKeyMap.put(path, watchKey);
return true;
} catch (IOException e) {
logger.warning(e, "Cannot watch directory %s.", path);
}
return false;
}
private synchronized void unwatchDirectory(Path path) {
Path normalizedPath = path.normalize();
if (!watchKeyMap.containsKey(normalizedPath)) {
logger.info("Directory %s is not being watched.", path);
return;
}
WatchKey watchKey = watchKeyMap.remove(normalizedPath);
watchKey.cancel();
}
synchronized void watchFileSnapshotPath(Path path) {
Path normalizedPath = path.normalize();
fileSnapshotPaths.add(path);
}
synchronized void unwatchFileSnapshotPath(Path path) {
Path normalizedPath = path.normalize();
fileSnapshotPaths.remove(path);
}
synchronized void shutdown() {
try {
watchService.close();
} catch (IOException e) {
// Ignore.
}
if (watchFuture != null) {
watchFuture.cancel(true /* mayInterrupt */);
watchFuture = null;
}
watchKeyMap.clear();
fileSnapshotPaths.clear();
}
synchronized void notifyFileChange(Path path, WatchEvent.Kind<?> eventKind) {
logger.fine("path: %s", path);
if (PathUtils.shouldIgnorePath(path, projectRoot, ignorePathMatchers)) {
return;
}
if (listener == null) {
return;
}
try {
listener.onFileChange(path, eventKind);
} catch (Throwable e) {
logger.warning(e, "File watch listener throws exception.");
}
}
private class WatchRunnable implements Runnable {
@Override
public void run() {
for (; ; ) {
WatchKey watchKey;
try {
watchKey = watchService.take();
} catch (ClosedWatchServiceException | InterruptedException e) {
// The watcher is shutdown, stop running
return;
}
@SuppressWarnings("unchecked")
Path dir = (Path) watchKey.watchable();
synchronized (FileWatcher.this) {
checkState(listener != null, "Watcher doesn't have listener");
for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
@SuppressWarnings("unchecked")
WatchEvent<Path> pathEvent = (WatchEvent<Path>) watchEvent;
handleWatchEvent(dir, pathEvent);
}
watchKey.reset();
}
}
}
private void handleWatchEvent(Path dir, WatchEvent<Path> event) {
WatchEvent.Kind<?> eventKind = event.kind();
if (eventKind == StandardWatchEventKinds.OVERFLOW) {
return;
}
Path fullPath = dir.resolve(event.context());
if (PathUtils.shouldIgnorePath(fullPath, projectRoot, ignorePathMatchers)) {
logger.fine("%s ignored", fullPath);
return;
}
if (fileSnapshotPaths.contains(fullPath)) {
logger.fine("%s is on fileSnapshotPaths", fullPath);
// The file is managed by file snapshots. Ignore file system events.
return;
}
if (Files.isDirectory(fullPath)) {
logger.fine("%s is a directory", fullPath);
handleDirectoryEvent(fullPath, eventKind);
return;
}
notifyFileChange(fullPath, event.kind());
}
private void handleDirectoryEvent(Path path, WatchEvent.Kind<?> eventKind) {
logger.fine("path:%s", path);
if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {
// New directory created, watch it.
watchNewDirectory(path);
} else if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {
unwatchDirectory(path);
}
}
private void watchNewDirectory(Path path) {
Queue<Path> newDirectories = new LinkedList<>();
Queue<Path> newFiles = new LinkedList<>();
newDirectories.add(path);
while (!newDirectories.isEmpty()) {
Path dir = newDirectories.remove();
if (!watchDirectory(dir)) {
// The directory is being monitored, skip files under it.
continue;
}
// There may be delay between the directory is created and the event is signaled.
// During such delay new files may be created. List all files in the directory and
// explicitly
// call listeners and watch new subdirectories.
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir)) {
for (Path file : directoryStream) {
if (Files.isDirectory(file)) {
newDirectories.add(file);
} else {
newFiles.add(file);
}
}
} catch (Throwable t) {
logger.severe(t, "Cannot list files in directory %s", path);
}
}
for (Path newFile : newFiles) {
notifyFileChange(newFile, StandardWatchEventKinds.ENTRY_CREATE);
}
}
}
}