Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Soft delete projects by moving them to trash #10440

Merged
merged 34 commits into from
Jul 27, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
f8f0c08
feat: trash
4e6 Jul 1, 2024
0e580d6
feat: move project to trash
4e6 Jul 3, 2024
8ffa14f
fix: TrashTest on Windows
4e6 Jul 4, 2024
b0ff163
fix: native image
4e6 Jul 4, 2024
569261f
Merge branch 'develop' into wip/db/10357-add-recycle
4e6 Jul 4, 2024
aa555cc
fix: after merge
4e6 Jul 4, 2024
ff4cbec
DEBUG: lazy trash initialization
4e6 Jul 5, 2024
3c90113
DEBUG: trash initialization
4e6 Jul 5, 2024
80dd6c8
DEBUG: awt initialization
4e6 Jul 5, 2024
df166a7
misc: javafmt
4e6 Jul 8, 2024
5fcd03c
misc: properties setup
4e6 Jul 8, 2024
efd9e05
fix: native image
4e6 Jul 8, 2024
bf177bf
feat: jna trash
4e6 Jul 9, 2024
170284b
feat: native image resources
4e6 Jul 9, 2024
b0d72f0
misc: cleanup properties setup
4e6 Jul 9, 2024
e97b44d
misc: legal review
4e6 Jul 9, 2024
1d296ef
Merge branch 'develop' into wip/db/10357-add-recycle
4e6 Jul 9, 2024
9aa46a8
fix: after merge
4e6 Jul 9, 2024
633f78a
Simplify LazyTrash by initializing in static initializer
JaroslavTulach Jul 21, 2024
e474e39
Making Platform an enum
JaroslavTulach Jul 21, 2024
c82ed2f
Merge branch 'develop' into wip/db/10357-add-recycle
hubertp Jul 23, 2024
0d346f2
Include Jaroslav's prototype
hubertp Jul 23, 2024
9066faa
os dependent
hubertp Jul 23, 2024
081c9d2
fmt
hubertp Jul 23, 2024
8e1e2b8
Fix native image build on linux
hubertp Jul 24, 2024
5a7d9c8
Merge branch 'develop' into wip/db/10357-add-recycle
hubertp Jul 25, 2024
961aa6c
remove jna
hubertp Jul 25, 2024
ccb8bd5
update license
hubertp Jul 25, 2024
0de3f1e
nit
hubertp Jul 25, 2024
2301840
fmt
hubertp Jul 26, 2024
114cdca
Fix tests that broke during Platform refactoring
hubertp Jul 26, 2024
20b892f
Workaround for non-AOT mode
hubertp Jul 26, 2024
c5aee4a
deal with non-empty directories for fallback delete
hubertp Jul 26, 2024
f6d66ab
fix: tests
4e6 Jul 27, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -1106,6 +1106,10 @@ lazy val `project-manager` = (project in file("lib/scala/project-manager"))
staticOnLinux = true,
initializeAtRuntime = Seq(
"scala.util.Random",
"sun.awt",
"sun.java2d",
"sun.font",
"java.awt",
"zio.internal.ZScheduler$$anon$4",
"zio.Runtime$",
"zio.FiberRef$"
Expand Down Expand Up @@ -2813,6 +2817,7 @@ lazy val `desktop-environment` =
.settings(
frgaalJavaCompilerSetting,
libraryDependencies ++= Seq(
"commons-io" % "commons-io" % commonsIoVersion,
"junit" % "junit" % junitVersion % Test,
"com.github.sbt" % "junit-interface" % junitIfVersion % Test
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package org.enso.desktopenvironment;

import java.awt.Desktop;
import java.nio.file.Files;
import java.nio.file.Path;

/** The {@link Trash} implementation provided by Java Abstract Window Toolkit. */
final class AwtTrash implements Trash {

private final Desktop desktop = Desktop.getDesktop();

@Override
public boolean isSupported() {
return desktop.isSupported(Desktop.Action.MOVE_TO_TRASH);
}

@Override
public boolean moveToTrash(Path path) {
if (Files.exists(path) && isSupported()) {
return desktop.moveToTrash(path.toFile());
} else {
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,11 @@ final class DirectoriesFactory {
private static final Directories INSTANCE = initDirectories();

private static Directories initDirectories() {
if (Platform.isLinux()) {
return new LinuxDirectories();
}

if (Platform.isMacOs()) {
return new MacOsDirectories();
}

if (Platform.isWindows()) {
return new WindowsDirectories();
}

throw new UnsupportedOperationException("Unsupported OS '" + Platform.getOsName() + "'");
return switch (Platform.getOperatingSystem()) {
case LINUX -> new LinuxDirectories();
case MACOS -> new MacOsDirectories();
case WINDOWS -> new WindowsDirectories();
};
}

private DirectoriesFactory() {}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
package org.enso.desktopenvironment;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import org.apache.commons.io.FileUtils;

/**
* The Linux trash implementing the <a
* href="https://specifications.freedesktop.org/trash-spec/trashspec-1.0.html">FreeDesktop.org Trash
* specification</a>.
*
* <p>A trash directory contains two subdirectories, named info and files. The files directory
* contains the trashed files, and the info directory contains the corresponding trashinfo metadata
* for each trashed entry in the files directory.
*/
final class LinuxTrash implements Trash {

private static final String XDG_DATA_HOME = "XDG_DATA_HOME";
private static final String PATH_TRASH = "Trash";
private static final String PATH_FILES = "files";
private static final String PATH_INFO = "info";

private final LinuxDirectories directories = new LinuxDirectories();

@Override
public boolean isSupported() {
var trashDir = detectTrashDirectory();
return Files.isDirectory(trashDir.resolve(PATH_FILES))
&& Files.isDirectory(trashDir.resolve(PATH_INFO));
}

@Override
public boolean moveToTrash(Path path) {
var trashDir = detectTrashDirectory();

if (Files.exists(path) && isSupported()) {
try {
var trashInfo = TrashInfo.create(trashDir.resolve(PATH_INFO), path);

try {
Files.move(
path,
trashDir.resolve(PATH_FILES).resolve(trashInfo.fileName),
StandardCopyOption.ATOMIC_MOVE);
return true;
} catch (IOException e) {
boolean isSuccessful;
if (Files.isDirectory(path)) {
isSuccessful =
moveDirectoryToDirectory(path, trashDir.resolve(PATH_FILES), trashInfo.fileName);
} else {
isSuccessful =
moveFileToDirectory(path, trashDir.resolve(PATH_FILES), trashInfo.fileName);
}

if (!isSuccessful) {
FileUtils.deleteQuietly(trashInfo.path.toFile());
}

return isSuccessful;
}
} catch (IOException e) {
return false;
}

} else {
return false;
}
}

private static boolean moveFileToDirectory(Path from, Path to, String fileName) {
var source = from.toFile();
var destination = to.resolve(fileName).toFile();

try {
FileUtils.copyFile(source, destination);
FileUtils.delete(source);

return true;
} catch (IOException e) {
FileUtils.deleteQuietly(destination);
return false;
}
}

private static boolean moveDirectoryToDirectory(Path from, Path to, String fileName) {
var source = from.toFile();
var destination = to.resolve(fileName).toFile();
try {
FileUtils.copyDirectory(source, destination);
FileUtils.deleteDirectory(source);

return true;
} catch (IOException e) {
FileUtils.deleteQuietly(destination);
return false;
}
}

/**
* Detect the path to a home trash directory of the current user.
*
* <p>The home trash directory should be automatically created for any new user. If the directory
* does not exist, it will be created.
*
* @return the path to the trash directory.
*/
private Path detectTrashDirectory() {
var xdgDataHomeOverride = System.getenv(XDG_DATA_HOME);
var xdgDataHome =
xdgDataHomeOverride == null
? directories.getUserHome().resolve(".local").resolve("share")
: Path.of(xdgDataHomeOverride);

var trashDir = xdgDataHome.resolve(PATH_TRASH);

try {
Files.createDirectories(trashDir.resolve(PATH_FILES));
} catch (IOException ignored) {
}

try {
Files.createDirectories(trashDir.resolve(PATH_INFO));
} catch (IOException ignored) {
}

return trashDir;
}

/**
* The trashinfo metadata file.
*
* @param path the path to this trashinfo file.
* @param fileName the file name that should be used to store the trashed file.
*/
private record TrashInfo(Path path, String fileName) {

private static final int SUFFIX_SIZE = 6;
private static final int MAX_ATTEMPTS = Byte.MAX_VALUE;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just use 127 constant here? Is the maximum number of attempts really tied to the representable range of Byte?

private static final String TRASHINFO_EXTENSION = ".trashinfo";

/**
* Create the .trashinfo file containing the deleted file metadata.
*
* @param trashInfo the path to the trashinfo directory.
* @param toDelete the path to the file that should be deleted.
* @return the trashinfo metadata file.
* @throws IOException if the file creation was unsuccessful.
*/
public static TrashInfo create(Path trashInfo, Path toDelete) throws IOException {
var builder = new StringBuilder();
builder.append("[Trash Info]");
builder.append(System.lineSeparator());
builder.append("Path=");
builder.append(toDelete.toAbsolutePath());
builder.append(System.lineSeparator());
builder.append("DeletionDate=");
builder.append(
LocalDateTime.now()
.truncatedTo(ChronoUnit.SECONDS)
.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
builder.append(System.lineSeparator());

return createTrashInfo(trashInfo, toDelete, builder, "", 0);
}

/**
* Create the .trashinfo file containing the deleted file metadata.
*
* <p>In case of a name clash, when the trash already contains the file with the same name, the
* trashinfo file is created with a random suffix to resolve the conflict.
*
* <p>The file creation is atomic to so that if two processes try trash files with the same
* filename this will result in two different trash files.
*
* @param trashInfo the path to the trashinfo directory.
* @param toDelete the path to the file that should be deleted.
* @param contents the trashinfo file contents.
* @param suffix the trashinfo suffix to resolve the file name conflicts.
* @param attempts the number of attempts to resolve the name clash.
* @return the trashinfo metadata file.
* @throws IOException if the file creation was unsuccessful.
*/
private static TrashInfo createTrashInfo(
Path trashInfo, Path toDelete, CharSequence contents, String suffix, int attempts)
throws IOException {
if (attempts > MAX_ATTEMPTS) {
throw new IOException("Failed to create trashinfo file. Max attempts reached.");
}

try {
var fileName = toDelete.getFileName().toString() + suffix;
var path =
Files.writeString(
trashInfo.resolve(fileName + TRASHINFO_EXTENSION),
contents,
StandardCharsets.UTF_8,
StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE);

return new TrashInfo(path, fileName);
} catch (FileAlreadyExistsException e) {
return createTrashInfo(
trashInfo,
toDelete,
contents,
RandomUtils.alphanumericString(SUFFIX_SIZE),
attempts + 1);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,56 @@ public final class Platform {
private static final String MAC = "mac";
private static final String WINDOWS = "windows";

private static final OS OPERATING_SYSTEM = detectOperatingSystem();

private Platform() {}

public static String getOsName() {
return System.getProperty(OS_NAME);
public enum OS {
hubertp marked this conversation as resolved.
Show resolved Hide resolved
LINUX,
MACOS,
WINDOWS
}

private static OS detectOperatingSystem() {
var osName = System.getProperty(OS_NAME);
var lowerOsName = osName.toLowerCase();

if (lowerOsName.contains(LINUX)) {
return OS.LINUX;
}

if (lowerOsName.contains(MAC)) {
return OS.MACOS;
}

if (lowerOsName.contains(WINDOWS)) {
return OS.WINDOWS;
}

throw new IllegalStateException("Unknown Operrating System: '" + osName + "'");
}

public static OS getOperatingSystem() {
return OPERATING_SYSTEM;
}

public static boolean isLinux() {
return getOsName().toLowerCase().contains(LINUX);
return OPERATING_SYSTEM == OS.LINUX;
}

public static boolean isMacOs() {
return getOsName().toLowerCase().contains(MAC);
return OPERATING_SYSTEM == OS.MACOS;
}

public static boolean isWindows() {
return getOsName().toLowerCase().contains(WINDOWS);
return OPERATING_SYSTEM == OS.WINDOWS;
}

public static Directories getDirectories() {
return DirectoriesFactory.getInstance();
}

public static Trash getTrash() {
return TrashFactory.getInstance();
}
}
Loading
Loading