Polish "Add support for symlinks in FileWatcher"

See gh-43586
This commit is contained in:
Stéphane Nicoll 2024-12-24 10:20:56 +01:00
parent 26ca3790b2
commit 916705538e
2 changed files with 26 additions and 11 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -86,7 +86,11 @@ class FileWatcher implements Closeable {
this.thread = new WatcherThread();
this.thread.start();
}
this.thread.register(new Registration(resolveSymlinks(paths), action));
Set<Path> actualPaths = new HashSet<>();
for (Path path : paths) {
actualPaths.add(resolveSymlinkIfNecessary(path));
}
this.thread.register(new Registration(actualPaths, action));
}
catch (IOException ex) {
throw new UncheckedIOException("Failed to register paths for watching: " + paths, ex);
@ -94,15 +98,12 @@ class FileWatcher implements Closeable {
}
}
private Set<Path> resolveSymlinks(Set<Path> paths) throws IOException {
Set<Path> result = new HashSet<>();
for (Path path : paths) {
result.add(path);
if (Files.isSymbolicLink(path)) {
result.add(Files.readSymbolicLink(path));
}
private static Path resolveSymlinkIfNecessary(Path path) throws IOException {
if (Files.isSymbolicLink(path)) {
Path target = Files.readSymbolicLink(path);
return resolveSymlinkIfNecessary(target);
}
return result;
return path;
}
@Override

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -106,6 +106,20 @@ class FileWatcherTests {
callback.expectChanges();
}
@Test
void shouldFollowSymlinkRecursively(@TempDir Path tempDir) throws Exception {
Path realFile = tempDir.resolve("realFile.txt");
Path symLink = tempDir.resolve("symlink.txt");
Path symLink2 = tempDir.resolve("symlink2.txt");
Files.createFile(realFile);
Files.createSymbolicLink(symLink, symLink2);
Files.createSymbolicLink(symLink2, realFile);
WaitingCallback callback = new WaitingCallback();
this.fileWatcher.watch(Set.of(symLink), callback);
Files.writeString(realFile, "Some content");
callback.expectChanges();
}
@Test
void shouldIgnoreNotWatchedFiles(@TempDir Path tempDir) throws Exception {
Path watchedFile = tempDir.resolve("watched.txt");