This is an automated email from the ASF dual-hosted git repository.
hansva pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/hop.git
The following commit(s) were added to refs/heads/main by this push:
new c857611a94 VFS File Explorer follows links to folders when deleting,
moving and … (#9370)
c857611a94 is described below
commit c857611a94ceb9d402f2956b0f8b3c1c9904be0c
Author: Bart Maertens <[email protected]>
AuthorDate: Thu Nov 12 10:46:44 2026 +0100
VFS File Explorer follows links to folders when deleting, moving and …
(#9370)
* VFS File Explorer follows links to folders when deleting, moving and
copying, fixes #9315
* Address review on #9315: junctions, links back into the source, link
loops, moves across disks
---
.../hopgui/vfs/explorer/VfsFileExplorerTest.java | 41 +-
.../perspective/explorer/ExplorerPerspective.java | 16 +-
.../hopgui/vfs/explorer/VfsExplorerOperation.java | 28 +-
.../ui/hopgui/vfs/explorer/VfsFileTransfer.java | 496 ++++++++++++++++++---
.../explorer/messages/messages_en_US.properties | 1 +
.../hopgui/vfs/explorer/VfsExplorerStatusTest.java | 13 +
.../hopgui/vfs/explorer/VfsFileTransferTest.java | 438 ++++++++++++++++++
7 files changed, 971 insertions(+), 62 deletions(-)
diff --git
a/rcp/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileExplorerTest.java
b/rcp/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileExplorerTest.java
index d2aa32ad53..6be601df01 100644
---
a/rcp/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileExplorerTest.java
+++
b/rcp/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileExplorerTest.java
@@ -25,6 +25,7 @@ import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
+import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
@@ -35,13 +36,14 @@ import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
+import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Drives a real VFS File Explorer through the paths that change files: a
paste onto an existing
- * file, and deleting the folder that is being shown.
+ * file, deleting the folder that is being shown, and deleting a link to a
folder.
*/
@Tag("uitest")
class VfsFileExplorerTest extends SwtBotTestBase {
@@ -121,6 +123,43 @@ class VfsFileExplorerTest extends SwtBotTestBase {
assertFalse(Files.exists(shown));
}
+ @Test
+ void deletingALinkToAFolderKeepsTheFilesItPointsTo() throws Exception {
+ Path real = Files.createDirectory(folder.resolve("real"));
+ Path keep = Files.writeString(real.resolve("keep.txt"), "keep");
+ Path view = Files.createDirectory(folder.resolve("view"));
+ Path link;
+ try {
+ link = Files.createSymbolicLink(view.resolve("link"), real);
+ } catch (UnsupportedOperationException | IOException e) {
+ Assumptions.abort("symbolic links are not available: " + e.getMessage());
+ return;
+ }
+
+ AtomicReference<VfsFileExplorer> explorer = new AtomicReference<>();
+ withScene(
+ shell -> explorer.set(createExplorer(shell, view)),
+ bot -> {
+ VfsFileExplorerLocation location = onUi(() ->
explorer.get().activeLocation());
+ waitForRows(location, 1);
+ onUi(
+ () -> {
+ location.fileTable().setSelection(0);
+ return null;
+ });
+
+ display.asyncExec(location::deleteSelectedFiles);
+ SWTBotShell confirm =
+ bot.shell(
+ BaseMessages.getString(VfsFileExplorer.PKG,
"VfsFileExplorer.Delete.Title"));
+
confirm.bot().button(BaseMessages.getString("System.Button.Yes")).click();
+ waitUntilIdle(explorer.get());
+ });
+
+ assertFalse(Files.exists(link, LinkOption.NOFOLLOW_LINKS));
+ assertEquals("keep", read(keep));
+ }
+
private static VfsFileExplorer createExplorer(
org.eclipse.swt.widgets.Shell shell, Path location) {
shell.setLayout(new FormLayout());
diff --git
a/ui/src/main/java/org/apache/hop/ui/hopgui/perspective/explorer/ExplorerPerspective.java
b/ui/src/main/java/org/apache/hop/ui/hopgui/perspective/explorer/ExplorerPerspective.java
index 1deccb793a..01ef1c99be 100644
---
a/ui/src/main/java/org/apache/hop/ui/hopgui/perspective/explorer/ExplorerPerspective.java
+++
b/ui/src/main/java/org/apache/hop/ui/hopgui/perspective/explorer/ExplorerPerspective.java
@@ -137,6 +137,7 @@ import org.apache.hop.ui.hopgui.shared.CanvasSvgHelper;
import org.apache.hop.ui.hopgui.shared.CanvasZoomHelper;
import org.apache.hop.ui.hopgui.shared.SashFormMemory;
import org.apache.hop.ui.hopgui.vfs.explorer.VfsFileExplorerViews;
+import org.apache.hop.ui.hopgui.vfs.explorer.VfsFileTransfer;
import org.apache.hop.ui.pipeline.transform.BaseTransformDialog;
import org.apache.hop.ui.util.EnvironmentUtils;
import org.apache.hop.workflow.WorkflowMeta;
@@ -1375,10 +1376,12 @@ public class ExplorerPerspective implements
IHopPerspective, TabClosable, IFileD
return;
}
+ // VfsFileTransfer.delete() removes a link by itself.
FileObject.deleteAll() would delete the
+ // files in the folder it points to.
+ //
if (fileObjects.size() == 1) {
- if (fileObjects.get(0).deleteAll() > 0) {
- removeTreeItemAfterDelete(items.get(0), filenamesPerItem.get(0));
- }
+ VfsFileTransfer.delete(fileObjects.get(0));
+ removeTreeItemAfterDelete(items.get(0), filenamesPerItem.get(0));
return;
}
@@ -1387,10 +1390,9 @@ public class ExplorerPerspective implements
IHopPerspective, TabClosable, IFileD
//
List<String> deletedFilenames = new ArrayList<>();
for (int i = 0; i < fileObjects.size(); i++) {
- if (fileObjects.get(i).deleteAll() > 0) {
- updateLastSelectedFolderAfterDelete(items.get(i));
- deletedFilenames.addAll(filenamesPerItem.get(i));
- }
+ VfsFileTransfer.delete(fileObjects.get(i));
+ updateLastSelectedFolderAfterDelete(items.get(i));
+ deletedFilenames.addAll(filenamesPerItem.get(i));
}
closeTabsForFilenames(deletedFilenames);
refresh();
diff --git
a/ui/src/main/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsExplorerOperation.java
b/ui/src/main/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsExplorerOperation.java
index aa18f8c748..4865c5d7d9 100644
---
a/ui/src/main/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsExplorerOperation.java
+++
b/ui/src/main/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsExplorerOperation.java
@@ -17,6 +17,9 @@
package org.apache.hop.ui.hopgui.vfs.explorer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import lombok.Getter;
@@ -50,6 +53,9 @@ public class VfsExplorerOperation {
private final AtomicLong bytesDone = new AtomicLong();
+ /** Folders a copy or move left out because a link led back into it, as
messages. */
+ private final List<String> skippedLinks = new CopyOnWriteArrayList<>();
+
public VfsExplorerOperation(String description, String location) {
this.description = description == null ? "" : description;
this.location = location == null ? "" : location;
@@ -80,7 +86,15 @@ public class VfsExplorerOperation {
return cancelled;
}
+ /**
+ * Done. A copy or move that left out a folder because of a link loop
transferred the rest, but
+ * ends as failed, so the folders it left out are shown.
+ */
public void complete() {
+ if (!cancelled && !skippedLinks.isEmpty()) {
+ fail(null, null);
+ return;
+ }
status = cancelled ? Status.CANCELLED : Status.DONE;
endTime = System.currentTimeMillis();
worker = null;
@@ -88,7 +102,12 @@ public class VfsExplorerOperation {
public void fail(String message, String detail) {
status = cancelled ? Status.CANCELLED : Status.FAILED;
- errorMessage = message;
+ List<String> lines = new ArrayList<>();
+ if (!isBlank(message)) {
+ lines.add(message);
+ }
+ lines.addAll(skippedLinks);
+ errorMessage = String.join("\n", lines);
this.detail = detail;
endTime = System.currentTimeMillis();
worker = null;
@@ -181,6 +200,13 @@ public class VfsExplorerOperation {
public void fileDone() {
filesDone.incrementAndGet();
}
+
+ @Override
+ public void linkLoopSkipped(String folder) {
+ skippedLinks.add(
+ BaseMessages.getString(
+ VfsFileExplorer.PKG, "VfsFileExplorer.Transfer.LinkLoop",
folder));
+ }
};
}
diff --git
a/ui/src/main/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileTransfer.java
b/ui/src/main/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileTransfer.java
index 2fcdc5ed69..40edbdc412 100644
---
a/ui/src/main/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileTransfer.java
+++
b/ui/src/main/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileTransfer.java
@@ -20,10 +20,17 @@ package org.apache.hop.ui.hopgui.vfs.explorer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.nio.file.FileVisitResult;
import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.function.BooleanSupplier;
@@ -38,6 +45,13 @@ import org.apache.hop.i18n.BaseMessages;
* Copy and move of VFS files and folders. Refuses a copy onto itself or into
its own child. An
* existing file is only replaced once its new content is completely written,
and an existing folder
* is merged rather than replaced.
+ *
+ * <p>A link on the local disk (a symbolic link, or a directory junction on
Windows) is deleted and
+ * moved as a link: the files it points to stay where they are. A move to
another local disk creates
+ * the link again there. A copy follows a link to a folder and copies what is
in it. A link that
+ * leads back to a folder the transfer is already in is skipped and reported,
and the rest is still
+ * transferred. A folder is not copied or moved onto or into the folder it
really is, also when a
+ * link leads there.
*/
public final class VfsFileTransfer {
@@ -80,6 +94,14 @@ public final class VfsFileTransfer {
void bytes(long count);
void fileDone();
+
+ /**
+ * {@code folder} was reached through a link and leads back to a folder
this transfer is already
+ * in, so it was left out. The rest is still transferred.
+ */
+ default void linkLoopSkipped(String folder) {
+ // Not reported.
+ }
}
/** Decides about one existing destination file. Called on the worker
thread. */
@@ -283,15 +305,38 @@ public final class VfsFileTransfer {
if (same(source, destination)) {
return Refusal.SAME;
}
- if (source.isFolder() && isInside(source, destinationFolder)) {
+ if (source.isFolder()
+ && (isInside(source, destinationFolder)
+ || realRefusal(source, destinationFolder) != Refusal.NONE)) {
return Refusal.INTO_ITSELF;
}
if (destination.exists()) {
- return destination.isFolder() == source.isFolder() ? Refusal.EXISTS :
Refusal.OTHER_KIND;
+ if (destination.isFolder() != source.isFolder()) {
+ return Refusal.OTHER_KIND;
+ }
+ Refusal real = source.isFolder() ? realRefusal(source, destination) :
Refusal.NONE;
+ return real == Refusal.NONE ? Refusal.EXISTS : real;
}
return Refusal.NONE;
}
+ /**
+ * Where two existing local folders really are, after following links.
{@link Refusal#SAME} when
+ * {@code target} is {@code source}, {@link Refusal#INTO_ITSELF} when it is
inside it. Merging
+ * into such a target would write every file onto itself, or into the folder
being read.
+ */
+ private static Refusal realRefusal(FileObject source, FileObject target) {
+ Path realSource = realPath(source);
+ Path realTarget = realPath(target);
+ if (realSource == null || realTarget == null) {
+ return Refusal.NONE;
+ }
+ if (realTarget.equals(realSource)) {
+ return Refusal.SAME;
+ }
+ return realTarget.startsWith(realSource) ? Refusal.INTO_ITSELF :
Refusal.NONE;
+ }
+
/**
* Copy or move {@code source} into {@code destinationFolder}, keeping the
base name. An existing
* folder is merged. Each existing file goes to {@code resolver}.
@@ -329,57 +374,173 @@ public final class VfsFileTransfer {
source,
destinationFolder.resolveFile(name),
mode,
- resolver,
- cancelled,
- progress == null ? Progress.NONE : progress);
+ new Walk(resolver, cancelled, progress == null ? Progress.NONE :
progress));
}
- private static void place(
- FileObject source,
- FileObject target,
- Mode mode,
- ConflictResolver resolver,
- BooleanSupplier cancelled,
- Progress progress)
+ /** What one transfer shares between the folders it goes through. */
+ private static final class Walk {
+ private final ConflictResolver resolver;
+ private final BooleanSupplier cancelled;
+ private final Progress progress;
+
+ /**
+ * The real paths of the local folders this transfer is reading or
writing, see {@link #enter}.
+ */
+ private final Set<Path> open = new HashSet<>();
+
+ /**
+ * While a link is moved into an existing folder: the files and folders it
placed where nothing
+ * was, so they can be removed again when that fails. Null otherwise.
+ */
+ private List<FileObject> created;
+
+ /** Files left where they are: skipped in the prompt, or reached again
through a link. */
+ private int skipped;
+
+ private Walk(ConflictResolver resolver, BooleanSupplier cancelled,
Progress progress) {
+ this.resolver = resolver;
+ this.cancelled = cancelled;
+ this.progress = progress;
+ }
+ }
+
+ private static void place(FileObject source, FileObject target, Mode mode,
Walk walk)
throws IOException {
- checkCancelled(cancelled);
+ checkCancelled(walk.cancelled);
if (!target.exists()) {
- if (mode == Mode.MOVE && source.canRenameTo(target)) {
+ if (mode == Mode.MOVE && canRename(source, target)) {
source.moveTo(target);
- progress.fileDone();
+ walk.progress.fileDone();
+ } else if (mode == Mode.MOVE) {
+ moveByCopy(source, target, walk);
} else {
- copyTree(source, target, cancelled, progress);
- if (mode == Mode.MOVE) {
- delete(source);
- }
+ copyTree(source, target, false, walk);
+ }
+ if (walk.created != null) {
+ walk.created.add(target);
}
return;
}
+ String name = source.getName().getBaseName();
if (source.isFolder() != target.isFolder()) {
- throw new RefusedException(Refusal.OTHER_KIND,
source.getName().getBaseName());
+ throw new RefusedException(Refusal.OTHER_KIND, name);
}
if (!source.isFolder()) {
- Resolution resolution = resolver == null ? Resolution.SKIP :
resolver.resolve(source, target);
+ Resolution resolution =
+ walk.resolver == null ? Resolution.SKIP :
walk.resolver.resolve(source, target);
if (resolution == Resolution.CANCEL) {
throw new CancellationException();
}
if (resolution == Resolution.REPLACE) {
- replaceFile(source, target, mode, cancelled, progress);
+ replaceFile(source, target, mode, walk.cancelled, walk.progress);
+ } else {
+ walk.skipped++;
}
return;
}
- for (FileObject child : source.getChildren()) {
- place(
- child,
- target.resolveFile(child.getName().getBaseName()),
- mode,
- resolver,
- cancelled,
- progress);
- }
- if (mode == Mode.MOVE && source.getChildren().length == 0) {
- // Skipped files stay behind, and so does the folder that holds them.
- source.delete();
+ Refusal real = realRefusal(source, target);
+ if (real != Refusal.NONE) {
+ throw new RefusedException(real, name);
+ }
+ if (mode == Mode.MOVE && localLink(source) != null) {
+ moveLinkInto(source, target, walk);
+ return;
+ }
+ Path entered = enter(walk, source);
+ if (entered == LOOP) {
+ return;
+ }
+ try {
+ for (FileObject child : source.getChildren()) {
+ place(child, target.resolveFile(child.getName().getBaseName()), mode,
walk);
+ }
+ } finally {
+ leave(walk, entered);
+ }
+ if (mode == Mode.MOVE) {
+ source.refresh();
+ if (source.getChildren().length == 0) {
+ // Skipped files stay behind, and so does the folder that holds them.
+ source.delete();
+ }
+ }
+ }
+
+ /**
+ * Move a link to a folder into the existing folder {@code target}. Moving
the files themselves
+ * would empty the folder the link points to, so they are copied and then
the link is removed. The
+ * link stays when a file was skipped. When the copy fails or is stopped,
the files and folders it
+ * created in {@code target} are removed again, so nothing is left twice.
+ */
+ private static void moveLinkInto(FileObject link, FileObject target, Walk
walk)
+ throws IOException {
+ int skippedBefore = walk.skipped;
+ Path entered = enter(walk, link);
+ if (entered == LOOP) {
+ return;
+ }
+ // The files are copied, so no other link is moved inside this one.
+ List<FileObject> created = new ArrayList<>();
+ walk.created = created;
+ try {
+ for (FileObject child : link.getChildren()) {
+ place(child, target.resolveFile(child.getName().getBaseName()),
Mode.COPY, walk);
+ }
+ } catch (IOException | RuntimeException e) {
+ for (int i = created.size() - 1; i >= 0; i--) {
+ try {
+ delete(created.get(i));
+ } catch (Exception ignored) {
+ // The failure itself is what gets reported.
+ }
+ }
+ throw e;
+ } finally {
+ leave(walk, entered);
+ walk.created = null;
+ }
+ if (walk.skipped == skippedBefore) {
+ delete(link);
+ }
+ }
+
+ /**
+ * True when a rename can move {@code source}. Commons VFS sees the whole
local disk as one file
+ * system, but a rename cannot move a file to another disk or partition.
+ */
+ private static boolean canRename(FileObject source, FileObject target) {
+ if (!source.canRenameTo(target)) {
+ return false;
+ }
+ Path from = localPath(source);
+ Path to = localPath(target);
+ if (from == null || to == null) {
+ return true;
+ }
+ try {
+ Path fromFolder = from.toAbsolutePath().getParent();
+ Path toFolder = to.toAbsolutePath().getParent();
+ if (fromFolder == null || toFolder == null) {
+ return true;
+ }
+ return Files.getFileStore(fromFolder.toRealPath())
+ .equals(Files.getFileStore(toFolder.toRealPath()));
+ } catch (IOException | RuntimeException e) {
+ // The rename reports what is wrong.
+ return true;
+ }
+ }
+
+ /**
+ * Move by copying and then deleting the source. A link is created again as
a link where it can
+ * be, so the files it points to are not copied. When a link loop was
skipped, the source stays.
+ */
+ private static void moveByCopy(FileObject source, FileObject target, Walk
walk)
+ throws IOException {
+ int skippedBefore = walk.skipped;
+ copyTree(source, target, true, walk);
+ if (walk.skipped == skippedBefore) {
+ delete(source);
}
}
@@ -433,14 +594,180 @@ public final class VfsFileTransfer {
}
}
+ /**
+ * Delete a file, or a folder with everything in it. A link is removed by
itself, also when it is
+ * inside the folder: the files it points to stay.
+ */
public static void delete(FileObject file) throws FileSystemException {
- if (file == null || !file.exists()) {
+ if (file == null) {
+ return;
+ }
+ Path path = localPath(file);
+ if (path == null) {
+ // Links are only known on the local disk. Elsewhere the provider
removes the whole tree.
+ if (file.exists()) {
+ file.delete(Selectors.SELECT_ALL);
+ }
+ return;
+ }
+ // Commons VFS sees a link to a folder as that folder:
Selectors.SELECT_ALL deletes what is in
+ // it, and the link is not removed while that folder holds files. So the
disk is walked
+ // directly, without following links.
+ try {
+ deleteLocal(path);
+ } catch (IOException e) {
+ throw new FileSystemException("vfs.provider/delete.error", e,
file.getName());
+ } finally {
+ file.refresh();
+ FileObject parent = file.getParent();
+ if (parent != null) {
+ parent.refresh();
+ }
+ }
+ }
+
+ private static void deleteLocal(Path path) throws IOException {
+ BasicFileAttributes attributes;
+ try {
+ attributes = Files.readAttributes(path, BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
+ } catch (NoSuchFileException e) {
+ return;
+ }
+ if (!attributes.isDirectory() || isLink(path, attributes)) {
+ Files.delete(path);
return;
}
- if (file.isFolder()) {
- file.delete(Selectors.SELECT_ALL);
- } else {
- file.delete();
+ Files.walkFileTree(
+ path,
+ new SimpleFileVisitor<>() {
+ @Override
+ public FileVisitResult preVisitDirectory(
+ Path folder, BasicFileAttributes folderAttributes) throws
IOException {
+ // A Windows junction is a folder to the walk. Remove it, not what
it points to.
+ if (!folder.equals(path) && isLink(folder, folderAttributes)) {
+ Files.delete(folder);
+ return FileVisitResult.SKIP_SUBTREE;
+ }
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult visitFile(Path file, BasicFileAttributes
fileAttributes)
+ throws IOException {
+ // Links are not followed, so a symbolic link to a folder arrives
here, as itself.
+ Files.delete(file);
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory(Path folder, IOException
e) throws IOException {
+ if (e != null) {
+ throw e;
+ }
+ Files.delete(folder);
+ return FileVisitResult.CONTINUE;
+ }
+ });
+ }
+
+ /** The path of a file on the local disk, or null when it is elsewhere. */
+ private static Path localPath(FileObject file) {
+ try {
+ if (file == null || !"file".equals(file.getName().getScheme())) {
+ return null;
+ }
+ String name = HopVfs.getFilename(file);
+ // A network share keeps its URI.
+ return name.startsWith("file:") ? null : Path.of(name);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ /**
+ * The path of a link on the local disk, or null when the file is not one. A
link is a symbolic
+ * link, or a directory junction on Windows.
+ */
+ static Path localLink(FileObject file) {
+ Path path = localPath(file);
+ if (path == null) {
+ return null;
+ }
+ try {
+ BasicFileAttributes attributes =
+ Files.readAttributes(path, BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
+ return isLink(path, attributes) ? path : null;
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ /**
+ * True for a symbolic link, and for a Windows directory junction ({@code
mklink /J}). Java does
+ * not count a junction as a symbolic link: it is a folder that is also
"other", a reparse point.
+ * Other reparse points, such as a cloud storage placeholder, are folders in
their own place, so a
+ * junction is told apart by its real path being somewhere else.
+ */
+ private static boolean isLink(Path path, BasicFileAttributes attributes) {
+ if (attributes.isSymbolicLink()) {
+ return true;
+ }
+ if (!attributes.isOther() || !attributes.isDirectory()) {
+ return false;
+ }
+ try {
+ Path absolute = path.toAbsolutePath();
+ Path folder = absolute.getParent();
+ return folder != null
+ &&
!absolute.toRealPath().equals(folder.toRealPath().resolve(absolute.getFileName()));
+ } catch (IOException e) {
+ // A junction whose folder is gone.
+ return true;
+ }
+ }
+
+ /** The real path of an existing local file, following links, or null. */
+ private static Path realPath(FileObject file) {
+ Path path = localPath(file);
+ if (path == null) {
+ return null;
+ }
+ try {
+ return path.toRealPath();
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ /** What {@link #enter} returns for a folder the transfer is already in. */
+ private static final Path LOOP = Path.of("");
+
+ /**
+ * Note that the transfer is in {@code folder}. Following links, a copy can
reach a folder it is
+ * already copying or writing into, and would then never end. Such a folder
is skipped and
+ * reported, and the rest is still transferred. Only local folders are
checked: the links are on
+ * the local disk.
+ *
+ * @return {@link #LOOP} when the transfer is already in this folder;
otherwise the real path to
+ * pass to {@link #leave}, or null when the folder is not local
+ */
+ private static Path enter(Walk walk, FileObject folder) {
+ Path real = realPath(folder);
+ if (real == null) {
+ // Not checked. Reading the folder reports what is wrong with it.
+ return null;
+ }
+ if (!walk.open.add(real)) {
+ walk.skipped++;
+ walk.progress.linkLoopSkipped(HopVfs.getFilename(folder));
+ return LOOP;
+ }
+ return real;
+ }
+
+ private static void leave(Walk walk, Path real) {
+ if (real != null && real != LOOP) {
+ walk.open.remove(real);
}
}
@@ -510,7 +837,22 @@ public final class VfsFileTransfer {
public static void copy(
FileObject source, FileObject target, BooleanSupplier cancelled,
Progress progress)
throws IOException {
- copyTree(source, target, cancelled, progress == null ? Progress.NONE :
progress);
+ copyTree(
+ source,
+ target,
+ false,
+ new Walk(null, cancelled, progress == null ? Progress.NONE :
progress));
+ }
+
+ /**
+ * Move {@code source} to {@code target}, which does not exist yet, by
copying and then deleting
+ * it, as a move to another disk does. A local link is created again as a
link.
+ */
+ static void moveByCopy(
+ FileObject source, FileObject target, BooleanSupplier cancelled,
Progress progress)
+ throws IOException {
+ moveByCopy(
+ source, target, new Walk(null, cancelled, progress == null ?
Progress.NONE : progress));
}
/** Put the original back after the new copy could not take its name. */
@@ -529,28 +871,76 @@ public final class VfsFileTransfer {
/**
* A folder this creates is removed again when the copy fails or is stopped,
with whatever was
* already copied into it.
+ *
+ * @param keepLinks create a local link again as a link instead of copying
what it points to, as
+ * for a move
*/
- private static void copyTree(
- FileObject source, FileObject target, BooleanSupplier cancelled,
Progress progress)
+ private static void copyTree(FileObject source, FileObject target, boolean
keepLinks, Walk walk)
throws IOException {
- checkCancelled(cancelled);
+ checkCancelled(walk.cancelled);
+ if (keepLinks && copyLink(source, target)) {
+ walk.progress.fileDone();
+ return;
+ }
if (!source.isFolder()) {
- copyFile(source, target, cancelled, progress);
+ copyFile(source, target, walk.cancelled, walk.progress);
return;
}
- target.createFolder();
+ Path realSource = enter(walk, source);
+ if (realSource == LOOP) {
+ return;
+ }
+ Path realTarget = null;
try {
- for (FileObject child : source.getChildren()) {
- copyTree(child, target.resolveFile(child.getName().getBaseName()),
cancelled, progress);
- }
- } catch (IOException | RuntimeException e) {
+ target.createFolder();
try {
- delete(target);
- } catch (Exception ignored) {
- // The failure itself is what gets reported.
+ // A link inside the source can lead into the folder being written.
That folder is new, so
+ // only a later source folder can match it.
+ realTarget = realPath(target);
+ if (realTarget != null && !walk.open.add(realTarget)) {
+ realTarget = null;
+ }
+ for (FileObject child : source.getChildren()) {
+ copyTree(child, target.resolveFile(child.getName().getBaseName()),
keepLinks, walk);
+ }
+ } catch (IOException | RuntimeException e) {
+ try {
+ delete(target);
+ } catch (Exception ignored) {
+ // The failure itself is what gets reported.
+ }
+ throw e;
}
- throw e;
+ } finally {
+ leave(walk, realTarget);
+ leave(walk, realSource);
+ }
+ }
+
+ /**
+ * Create the local link {@code source} again at {@code target}, pointing
where it points.
+ *
+ * @return false when {@code source} is not a local link, or the link cannot
be created there: a
+ * junction, a target that is not on the local disk, or no right to
create links (Windows
+ * without developer mode). The caller then copies what the link points
to.
+ */
+ private static boolean copyLink(FileObject source, FileObject target) {
+ Path link = localLink(source);
+ Path to = localPath(target);
+ if (link == null || to == null) {
+ return false;
+ }
+ try {
+ Files.createSymbolicLink(to, Files.readSymbolicLink(link));
+ } catch (IOException | UnsupportedOperationException | SecurityException
e) {
+ return false;
+ }
+ try {
+ target.refresh();
+ } catch (FileSystemException e) {
+ // Only the cached state; the link is in place.
}
+ return true;
}
/**
diff --git
a/ui/src/main/resources/org/apache/hop/ui/hopgui/vfs/explorer/messages/messages_en_US.properties
b/ui/src/main/resources/org/apache/hop/ui/hopgui/vfs/explorer/messages/messages_en_US.properties
index cc2094deed..48923f142d 100644
---
a/ui/src/main/resources/org/apache/hop/ui/hopgui/vfs/explorer/messages/messages_en_US.properties
+++
b/ui/src/main/resources/org/apache/hop/ui/hopgui/vfs/explorer/messages/messages_en_US.properties
@@ -120,6 +120,7 @@ VfsFileExplorer.Transfer.IntoItself=Cannot copy or move
''{0}'' into itself
VfsFileExplorer.Transfer.Exists=''{0}'' already exists
VfsFileExplorer.Transfer.OtherKind=Cannot replace ''{0}'': one is a file and
the other is a folder
VfsFileExplorer.Transfer.Failed=Could not copy or move ''{0}'': {1}
+VfsFileExplorer.Transfer.LinkLoop=Skipped ''{0}'': a link leads back to a
folder that is already part of this transfer.
VfsFileExplorer.Transfer.Stranded=''{0}'' could not be replaced. In the same
folder, the original is kept as the hidden file ''{1}'' and the new copy as
''{2}''.
VfsFileExplorer.Conflict.Title=File already exists
VfsFileExplorer.Conflict.Message=''{0}'' already exists in {1}.\nReplace it?
diff --git
a/ui/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsExplorerStatusTest.java
b/ui/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsExplorerStatusTest.java
index c07f303cab..770dedbfb7 100644
---
a/ui/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsExplorerStatusTest.java
+++
b/ui/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsExplorerStatusTest.java
@@ -87,6 +87,19 @@ class VfsExplorerStatusTest {
assertEquals("folder is gone", operation.getErrorMessage());
}
+ @Test
+ void aSkippedLinkLoopIsReportedWhenTheCopyEnds() {
+ VfsExplorerOperation operation = new VfsExplorerOperation("Copying",
"file:///tmp");
+ operation.progress().linkLoopSkipped("/data/self");
+ operation.complete();
+ assertEquals(VfsExplorerOperation.Status.FAILED, operation.getStatus());
+ assertTrue(operation.getErrorMessage().contains("/data/self"));
+
+ operation.fail(new IllegalStateException("disk full"));
+ assertTrue(operation.getErrorMessage().startsWith("disk full\n"));
+ assertTrue(operation.getErrorMessage().contains("/data/self"));
+ }
+
@Test
void stopWinsOverADriverFailure() {
VfsExplorerOperation operation = new VfsExplorerOperation("Listing",
"smb://share");
diff --git
a/ui/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileTransferTest.java
b/ui/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileTransferTest.java
index a7c9b9d684..792b89b1ad 100644
---
a/ui/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileTransferTest.java
+++
b/ui/src/test/java/org/apache/hop/ui/hopgui/vfs/explorer/VfsFileTransferTest.java
@@ -23,12 +23,14 @@ import static
org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.abort;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
+import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
@@ -41,6 +43,8 @@ import org.apache.hop.core.vfs.HopVfs;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledOnOs;
+import org.junit.jupiter.api.condition.OS;
class VfsFileTransferTest {
@@ -374,6 +378,440 @@ class VfsFileTransferTest {
}
}
+ @Test
+ void deletingALinkToAFolderKeepsTheFilesItPointsTo() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-delete-link");
+ try {
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Path keep = Files.writeString(real.resolve("keep.txt"), "keep");
+ Path view = Files.createDirectories(dir.resolve("view"));
+ Path link = symbolicLink(view.resolve("link"), real);
+
+ VfsFileTransfer.delete(HopVfs.getFileObject(link.toString()));
+
+ assertFalse(Files.exists(link, LinkOption.NOFOLLOW_LINKS));
+ assertEquals("keep", Files.readString(keep));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void deletingAFolderKeepsTheFilesOfALinkInsideIt() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-delete-folder-link");
+ try {
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Path keep = Files.writeString(real.resolve("keep.txt"), "keep");
+ Path view = Files.createDirectories(dir.resolve("view"));
+ Files.writeString(view.resolve("own.txt"), "own");
+ symbolicLink(view.resolve("link"), real);
+
+ VfsFileTransfer.delete(HopVfs.getFileObject(view.toString()));
+
+ assertFalse(Files.exists(view, LinkOption.NOFOLLOW_LINKS));
+ assertEquals("keep", Files.readString(keep));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void deletingABrokenLinkRemovesIt() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-delete-broken-link");
+ try {
+ Path link = symbolicLink(dir.resolve("link"), dir.resolve("gone"));
+
+ VfsFileTransfer.delete(HopVfs.getFileObject(link.toString()));
+
+ assertFalse(Files.exists(link, LinkOption.NOFOLLOW_LINKS));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void movingALinkToAnotherFileSystemKeepsTheFilesItPointsTo() throws
Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-move-link");
+ try {
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Path keep = Files.writeString(real.resolve("keep.txt"), "keep");
+ Path link =
symbolicLink(Files.createDirectories(dir.resolve("view")).resolve("link"),
real);
+ FileObject dest = folder(root, "dest");
+
+ VfsFileTransfer.transfer(
+ HopVfs.getFileObject(link.toString()), dest,
VfsFileTransfer.Mode.MOVE, SKIP, null);
+
+ assertEquals("keep", read(dest.resolveFile("link/keep.txt")));
+ assertFalse(Files.exists(link, LinkOption.NOFOLLOW_LINKS));
+ assertEquals("keep", Files.readString(keep));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void movingALinkOntoAnExistingFolderKeepsTheFilesItPointsTo() throws
Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-merge-link");
+ try {
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Path keep = Files.writeString(real.resolve("keep.txt"), "keep");
+ Path link =
symbolicLink(Files.createDirectories(dir.resolve("view")).resolve("link"),
real);
+ FileObject dest = folder(root, "dest");
+ folder(dest, "link");
+
+ VfsFileTransfer.transfer(
+ HopVfs.getFileObject(link.toString()), dest,
VfsFileTransfer.Mode.MOVE, SKIP, null);
+
+ assertEquals("keep", read(dest.resolveFile("link/keep.txt")));
+ assertFalse(Files.exists(link, LinkOption.NOFOLLOW_LINKS));
+ assertEquals("keep", Files.readString(keep));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void aMergedLinkMoveWithASkippedFileKeepsTheLink() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-merge-link-skip");
+ try {
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Path keep = Files.writeString(real.resolve("keep.txt"), "keep");
+ Path other = Files.writeString(real.resolve("other.txt"), "other");
+ Path link =
symbolicLink(Files.createDirectories(dir.resolve("view")).resolve("link"),
real);
+ FileObject dest = folder(root, "dest");
+ write(folder(dest, "link"), "keep.txt", "existing");
+
+ VfsFileTransfer.transfer(
+ HopVfs.getFileObject(link.toString()), dest,
VfsFileTransfer.Mode.MOVE, SKIP, null);
+
+ assertEquals("existing", read(dest.resolveFile("link/keep.txt")));
+ assertEquals("other", read(dest.resolveFile("link/other.txt")));
+ assertTrue(Files.isSymbolicLink(link));
+ assertEquals("keep", Files.readString(keep));
+ assertEquals("other", Files.readString(other));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void copyingAFolderFollowsALinkToAnotherFolder() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-copy-link");
+ try {
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Files.writeString(real.resolve("keep.txt"), "keep");
+ Path view = Files.createDirectories(dir.resolve("view"));
+ symbolicLink(view.resolve("link"), real);
+ FileObject dest = folder(root, "dest");
+
+ VfsFileTransfer.transfer(
+ HopVfs.getFileObject(view.toString()), dest,
VfsFileTransfer.Mode.COPY, SKIP, null);
+
+ assertEquals("keep", read(dest.resolveFile("view/link/keep.txt")));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void copyingALinkToItsOwnFolderSkipsItAndCopiesTheRest() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-copy-self");
+ try {
+ Path source = Files.createDirectories(dir.resolve("source"));
+ Files.writeString(source.resolve("a.txt"), "a");
+ Path self = symbolicLink(source.resolve("self"), Path.of("."));
+ Path dest = Files.createDirectories(dir.resolve("dest"));
+ List<String> skipped = new ArrayList<>();
+
+ VfsFileTransfer.transfer(
+ HopVfs.getFileObject(source.toString()),
+ HopVfs.getFileObject(dest.toString()),
+ VfsFileTransfer.Mode.COPY,
+ SKIP,
+ null,
+ skipping(skipped));
+
+ assertEquals(List.of(filename(self)), skipped);
+ assertEquals("a", Files.readString(dest.resolve("source/a.txt")));
+ assertFalse(Files.exists(dest.resolve("source/self"),
LinkOption.NOFOLLOW_LINKS));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void copyingALinkToAParentFolderSkipsTheLoopAndCopiesTheRest() throws
Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-copy-parent");
+ try {
+ Path parent = Files.createDirectories(dir.resolve("parent"));
+ Files.writeString(parent.resolve("big.txt"), "big");
+ Path sub = Files.createDirectories(parent.resolve("sub"));
+ Files.writeString(sub.resolve("own.txt"), "own");
+ symbolicLink(sub.resolve("up"), Path.of(".."));
+ Path dest = Files.createDirectories(dir.resolve("dest"));
+ List<String> skipped = new ArrayList<>();
+
+ VfsFileTransfer.transfer(
+ HopVfs.getFileObject(sub.toString()),
+ HopVfs.getFileObject(dest.toString()),
+ VfsFileTransfer.Mode.COPY,
+ SKIP,
+ null,
+ skipping(skipped));
+
+ assertEquals(List.of(filename(sub.resolve("up").resolve("sub"))),
skipped);
+ assertEquals("own", Files.readString(dest.resolve("sub/own.txt")));
+ assertEquals("big", Files.readString(dest.resolve("sub/up/big.txt")));
+ assertFalse(Files.exists(dest.resolve("sub/up/sub")));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void copyingALinkIntoTheFolderItPointsToIsRefused() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-copy-into-target");
+ try {
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Path keep = Files.writeString(real.resolve("keep.txt"), "keep");
+ Path link =
symbolicLink(Files.createDirectories(dir.resolve("view")).resolve("link"),
real);
+ FileObject source = HopVfs.getFileObject(link.toString());
+ FileObject destination = HopVfs.getFileObject(real.toString());
+
+ assertEquals(
+ VfsFileTransfer.Refusal.INTO_ITSELF, VfsFileTransfer.refusal(source,
destination));
+ VfsFileTransfer.RefusedException e =
+ assertThrows(
+ VfsFileTransfer.RefusedException.class,
+ () ->
+ VfsFileTransfer.transfer(
+ source, destination, VfsFileTransfer.Mode.COPY, SKIP,
null));
+
+ assertEquals(VfsFileTransfer.Refusal.INTO_ITSELF, e.getRefusal());
+ assertFalse(Files.exists(real.resolve("link")));
+ assertEquals("keep", Files.readString(keep));
+ assertTrue(Files.isSymbolicLink(link));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void movingAFolderOntoALinkToItselfIsRefused() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-move-onto-self");
+ try {
+ Path data = Files.createDirectories(dir.resolve("data/x"));
+ Path keep = Files.writeString(data.resolve("keep.txt"), "keep");
+ Path dest = Files.createDirectories(dir.resolve("dest"));
+ symbolicLink(dest.resolve("x"), data);
+ FileObject source = HopVfs.getFileObject(data.toString());
+ FileObject destination = HopVfs.getFileObject(dest.toString());
+
+ assertEquals(VfsFileTransfer.Refusal.SAME,
VfsFileTransfer.refusal(source, destination));
+ VfsFileTransfer.RefusedException e =
+ assertThrows(
+ VfsFileTransfer.RefusedException.class,
+ () ->
+ VfsFileTransfer.transfer(
+ source, destination, VfsFileTransfer.Mode.MOVE, REPLACE,
null));
+
+ assertEquals(VfsFileTransfer.Refusal.SAME, e.getRefusal());
+ assertEquals("keep", Files.readString(keep));
+ assertTrue(Files.isSymbolicLink(dest.resolve("x")));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void movingAFolderIsRefusedWhereALinkInTheTargetLeadsBackIntoIt() throws
Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-move-nested-self");
+ try {
+ Path x = Files.createDirectories(dir.resolve("src/p/x"));
+ Path keep = Files.writeString(x.resolve("keep.txt"), "keep");
+ Path existing = Files.createDirectories(dir.resolve("dest/p"));
+ symbolicLink(existing.resolve("x"), x);
+
+ VfsFileTransfer.RefusedException e =
+ assertThrows(
+ VfsFileTransfer.RefusedException.class,
+ () ->
+ VfsFileTransfer.transfer(
+ HopVfs.getFileObject(dir.resolve("src/p").toString()),
+ HopVfs.getFileObject(dir.resolve("dest").toString()),
+ VfsFileTransfer.Mode.MOVE,
+ REPLACE,
+ null));
+
+ assertEquals(VfsFileTransfer.Refusal.SAME, e.getRefusal());
+ assertEquals("keep", Files.readString(keep));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void aStoppedLinkMoveIntoAFolderRemovesWhatItCopied() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-merge-link-stop");
+ try {
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Files.writeString(real.resolve("a.txt"), "a");
+ Files.writeString(real.resolve("b.txt"), "b");
+ Files.writeString(real.resolve("c.txt"), "c");
+ Path link =
symbolicLink(Files.createDirectories(dir.resolve("view")).resolve("link"),
real);
+ FileObject dest = folder(root, "dest");
+ write(folder(dest, "link"), "own.txt", "own");
+ int[] files = {0};
+ VfsFileTransfer.Progress counting =
+ new VfsFileTransfer.Progress() {
+ @Override
+ public void bytes(long count) {
+ // Not counted.
+ }
+
+ @Override
+ public void fileDone() {
+ files[0]++;
+ }
+ };
+
+ assertThrows(
+ CancellationException.class,
+ () ->
+ VfsFileTransfer.transfer(
+ HopVfs.getFileObject(link.toString()),
+ dest,
+ VfsFileTransfer.Mode.MOVE,
+ SKIP,
+ () -> files[0] >= 1,
+ counting));
+
+ assertEquals(1, files[0]);
+ assertEquals(List.of("own.txt"), names(dest.resolveFile("link")));
+ assertTrue(Files.isSymbolicLink(link));
+ assertEquals(List.of("a.txt", "b.txt", "c.txt"), sorted(real));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ @Test
+ void aMoveByCopyCreatesTheLinksAgain() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-move-by-copy");
+ try {
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Path keep = Files.writeString(real.resolve("keep.txt"), "keep");
+ Path source = Files.createDirectories(dir.resolve("home/a"));
+ Files.writeString(source.resolve("own.txt"), "own");
+ symbolicLink(source.resolve("data"), real);
+ Path target = Files.createDirectories(dir.resolve("other")).resolve("a");
+
+ VfsFileTransfer.moveByCopy(
+ HopVfs.getFileObject(source.toString()),
+ HopVfs.getFileObject(target.toString()),
+ null,
+ null);
+
+ assertFalse(Files.exists(source, LinkOption.NOFOLLOW_LINKS));
+ assertEquals("own", Files.readString(target.resolve("own.txt")));
+ assertTrue(Files.isSymbolicLink(target.resolve("data")));
+ assertEquals(real, Files.readSymbolicLink(target.resolve("data")));
+ assertEquals("keep", Files.readString(keep));
+ assertEquals(List.of("keep.txt"), sorted(real));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ /**
+ * Commons VFS lets a rename try to move a folder to another local disk,
where it fails. Runs when
+ * the temporary folder and the build folder are on different disks.
+ */
+ @Test
+ void aMoveToAnotherDiskKeepsTheLinks() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-move-disk");
+ Path other = Files.createTempDirectory(Path.of("target").toAbsolutePath(),
"hop-vfs-move-disk");
+ try {
+ assumeFalse(
+ Files.getFileStore(dir).equals(Files.getFileStore(other)),
+ "the temporary folder and the build folder are on one disk");
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Path keep = Files.writeString(real.resolve("keep.txt"), "keep");
+ Path source = Files.createDirectories(dir.resolve("a"));
+ Files.writeString(source.resolve("own.txt"), "own");
+ symbolicLink(source.resolve("data"), real);
+
+ VfsFileTransfer.transfer(
+ HopVfs.getFileObject(source.toString()),
+ HopVfs.getFileObject(other.toString()),
+ VfsFileTransfer.Mode.MOVE,
+ SKIP,
+ null);
+
+ assertFalse(Files.exists(source, LinkOption.NOFOLLOW_LINKS));
+ assertEquals("own", Files.readString(other.resolve("a/own.txt")));
+ assertTrue(Files.isSymbolicLink(other.resolve("a/data")));
+ assertEquals("keep", Files.readString(keep));
+ } finally {
+ deleteTree(dir);
+ deleteTree(other);
+ }
+ }
+
+ @Test
+ @EnabledOnOs(OS.WINDOWS)
+ void deletingAFolderKeepsTheFilesOfAJunctionInsideIt() throws Exception {
+ Path dir = Files.createTempDirectory("hop-vfs-delete-junction");
+ try {
+ Path real = Files.createDirectories(dir.resolve("real"));
+ Path keep = Files.writeString(real.resolve("keep.txt"), "keep");
+ Path view = Files.createDirectories(dir.resolve("view"));
+ Path junction = view.resolve("junction");
+ Process mklink =
+ new ProcessBuilder("cmd", "/c", "mklink", "/J", junction.toString(),
real.toString())
+ .redirectErrorStream(true)
+ .start();
+ assertEquals(0, mklink.waitFor());
+ assertEquals(junction,
VfsFileTransfer.localLink(HopVfs.getFileObject(junction.toString())));
+
+ VfsFileTransfer.delete(HopVfs.getFileObject(view.toString()));
+
+ assertFalse(Files.exists(view, LinkOption.NOFOLLOW_LINKS));
+ assertEquals("keep", Files.readString(keep));
+ } finally {
+ deleteTree(dir);
+ }
+ }
+
+ private static VfsFileTransfer.Progress skipping(List<String> skipped) {
+ return new VfsFileTransfer.Progress() {
+ @Override
+ public void bytes(long count) {
+ // Not counted.
+ }
+
+ @Override
+ public void fileDone() {
+ // Not counted.
+ }
+
+ @Override
+ public void linkLoopSkipped(String folder) {
+ skipped.add(folder);
+ }
+ };
+ }
+
+ private static String filename(Path path) throws Exception {
+ return HopVfs.getFilename(HopVfs.getFileObject(path.toString()));
+ }
+
+ private static List<String> sorted(Path folder) throws Exception {
+ try (Stream<Path> paths = Files.list(folder)) {
+ return paths.map(path ->
path.getFileName().toString()).sorted().toList();
+ }
+ }
+
@Test
void aDroppedPathInsideAnotherIsLeftOut() {
assertEquals(