Moved all filename paring into its own class

This commit is contained in:
Szum123321 2022-08-30 13:28:30 +02:00
parent b3a340deab
commit 21cf46a56a
9 changed files with 231 additions and 256 deletions

View File

@ -20,12 +20,12 @@ package net.szum123321.textile_backup.commands;
import com.mojang.brigadier.LiteralMessage; import com.mojang.brigadier.LiteralMessage;
import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.suggestion.SuggestionProvider; import com.mojang.brigadier.suggestion.SuggestionProvider;
import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder; import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.Globals; import net.szum123321.textile_backup.Globals;
import net.szum123321.textile_backup.core.RestoreableFile;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import net.szum123321.textile_backup.core.restore.RestoreHelper; import net.szum123321.textile_backup.core.restore.RestoreHelper;
@ -42,7 +42,7 @@ public final class FileSuggestionProvider implements SuggestionProvider<ServerCo
public CompletableFuture<Suggestions> getSuggestions(CommandContext<ServerCommandSource> ctx, SuggestionsBuilder builder) { public CompletableFuture<Suggestions> getSuggestions(CommandContext<ServerCommandSource> ctx, SuggestionsBuilder builder) {
String remaining = builder.getRemaining(); String remaining = builder.getRemaining();
for (RestoreHelper.RestoreableFile file : RestoreHelper.getAvailableBackups(ctx.getSource().getServer())) { for (RestoreableFile file : RestoreHelper.getAvailableBackups(ctx.getSource().getServer())) {
String formattedCreationTime = file.getCreationTime().format(Globals.defaultDateTimeFormatter); String formattedCreationTime = file.getCreationTime().format(Globals.defaultDateTimeFormatter);
if (formattedCreationTime.startsWith(remaining)) { if (formattedCreationTime.startsWith(remaining)) {
@ -61,6 +61,7 @@ public final class FileSuggestionProvider implements SuggestionProvider<ServerCo
} }
} }
} }
return builder.buildFuture(); return builder.buildFuture();
} }
} }

View File

@ -28,6 +28,7 @@ import net.szum123321.textile_backup.TextileBackup;
import net.szum123321.textile_backup.TextileLogger; import net.szum123321.textile_backup.TextileLogger;
import net.szum123321.textile_backup.commands.CommandExceptions; import net.szum123321.textile_backup.commands.CommandExceptions;
import net.szum123321.textile_backup.commands.FileSuggestionProvider; import net.szum123321.textile_backup.commands.FileSuggestionProvider;
import net.szum123321.textile_backup.core.RestoreableFile;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import java.io.IOException; import java.io.IOException;
@ -35,7 +36,7 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeParseException; import java.time.format.DateTimeParseException;
import java.util.stream.Stream; import java.util.Optional;
public class DeleteCommand { public class DeleteCommand {
private final static TextileLogger log = new TextileLogger(TextileBackup.MOD_NAME); private final static TextileLogger log = new TextileLogger(TextileBackup.MOD_NAME);
@ -59,30 +60,29 @@ public class DeleteCommand {
Path root = Utilities.getBackupRootPath(Utilities.getLevelName(source.getServer())); Path root = Utilities.getBackupRootPath(Utilities.getLevelName(source.getServer()));
try (Stream<Path> stream = Files.list(root)) { RestoreableFile.applyOnFiles(root, Optional.empty(),
stream.filter(Utilities::isValidBackup) e -> {
.filter(file -> Utilities.getFileCreationTime(file).orElse(LocalDateTime.MIN).equals(dateTime)) log.sendError(source, "Couldn't find file by this name.");
.findFirst().ifPresent(file -> { log.sendHint(source, "Maybe try /backup list");
if(Globals.INSTANCE.getLockedFile().filter(p -> p == file).isEmpty()) { },
try { stream -> stream.filter(f -> f.getCreationTime().equals(dateTime)).map(RestoreableFile::getFile).findFirst()
Files.delete(file); ).ifPresent(file -> {
log.sendInfo(source, "File {} successfully deleted!", file); if(Globals.INSTANCE.getLockedFile().filter(p -> p == file).isEmpty()) {
try {
Files.delete((Path) file);
log.sendInfo(source, "File {} successfully deleted!", file);
if(Utilities.wasSentByPlayer(source)) if(Utilities.wasSentByPlayer(source))
log.info("Player {} deleted {}.", source.getPlayer().getName(), file); log.info("Player {} deleted {}.", source.getPlayer().getName(), file);
} catch (IOException e) { } catch (IOException e) {
log.sendError(source, "Something went wrong while deleting file!"); log.sendError(source, "Something went wrong while deleting file!");
}
} else {
log.sendError(source, "Couldn't delete the file because it's being restored right now.");
log.sendHint(source, "If you want to abort restoration then use: /backup killR");
} }
}); } else {
} catch (IOException ignored) { log.sendError(source, "Couldn't delete the file because it's being restored right now.");
log.sendError(source, "Couldn't find file by this name."); log.sendHint(source, "If you want to abort restoration then use: /backup killR");
log.sendHint(source, "Maybe try /backup list"); }
} }
);
return 0; return 0;
} }
} }

View File

@ -23,6 +23,7 @@ import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.TextileBackup;
import net.szum123321.textile_backup.TextileLogger; import net.szum123321.textile_backup.TextileLogger;
import net.szum123321.textile_backup.core.RestoreableFile;
import net.szum123321.textile_backup.core.restore.RestoreHelper; import net.szum123321.textile_backup.core.restore.RestoreHelper;
import java.util.*; import java.util.*;
@ -33,7 +34,7 @@ public class ListBackupsCommand {
public static LiteralArgumentBuilder<ServerCommandSource> register() { public static LiteralArgumentBuilder<ServerCommandSource> register() {
return CommandManager.literal("list") return CommandManager.literal("list")
.executes(ctx -> { StringBuilder builder = new StringBuilder(); .executes(ctx -> { StringBuilder builder = new StringBuilder();
List<RestoreHelper.RestoreableFile> backups = RestoreHelper.getAvailableBackups(ctx.getSource().getServer()); List<RestoreableFile> backups = RestoreHelper.getAvailableBackups(ctx.getSource().getServer());
if(backups.size() == 0) { if(backups.size() == 0) {
builder.append("There a no backups available for this world."); builder.append("There a no backups available for this world.");
@ -42,7 +43,7 @@ public class ListBackupsCommand {
builder.append(backups.get(0).toString()); builder.append(backups.get(0).toString());
} else { } else {
backups.sort(null); backups.sort(null);
Iterator<RestoreHelper.RestoreableFile> iterator = backups.iterator(); Iterator<RestoreableFile> iterator = backups.iterator();
builder.append("Available backups:\n"); builder.append("Available backups:\n");
builder.append(iterator.next()); builder.append(iterator.next());

View File

@ -29,6 +29,7 @@ import net.szum123321.textile_backup.TextileBackup;
import net.szum123321.textile_backup.TextileLogger; import net.szum123321.textile_backup.TextileLogger;
import net.szum123321.textile_backup.commands.CommandExceptions; import net.szum123321.textile_backup.commands.CommandExceptions;
import net.szum123321.textile_backup.commands.FileSuggestionProvider; import net.szum123321.textile_backup.commands.FileSuggestionProvider;
import net.szum123321.textile_backup.core.RestoreableFile;
import net.szum123321.textile_backup.core.restore.RestoreContext; import net.szum123321.textile_backup.core.restore.RestoreContext;
import net.szum123321.textile_backup.core.restore.RestoreHelper; import net.szum123321.textile_backup.core.restore.RestoreHelper;
@ -84,7 +85,7 @@ public class RestoreBackupCommand {
throw CommandExceptions.DATE_TIME_PARSE_COMMAND_EXCEPTION_TYPE.create(e); throw CommandExceptions.DATE_TIME_PARSE_COMMAND_EXCEPTION_TYPE.create(e);
} }
Optional<RestoreHelper.RestoreableFile> backupFile = RestoreHelper.findFileAndLockIfPresent(dateTime, source.getServer()); Optional<RestoreableFile> backupFile = RestoreHelper.findFileAndLockIfPresent(dateTime, source.getServer());
if(backupFile.isPresent()) { if(backupFile.isPresent()) {
log.info("Found file to restore {}", backupFile.get().getFile().getFileName().toString()); log.info("Found file to restore {}", backupFile.get().getFile().getFileName().toString());

View File

@ -19,7 +19,7 @@
package net.szum123321.textile_backup.core; package net.szum123321.textile_backup.core;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.Globals; import net.szum123321.textile_backup.Globals;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.TextileBackup;
import net.szum123321.textile_backup.TextileLogger; import net.szum123321.textile_backup.TextileLogger;
@ -30,7 +30,6 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.util.Comparator;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -43,106 +42,85 @@ public class Cleanup {
Path root = Utilities.getBackupRootPath(worldName); Path root = Utilities.getBackupRootPath(worldName);
int deletedFiles = 0; int deletedFiles = 0;
if (Files.isDirectory(root) && Files.exists(root) && !isEmpty(root)) { if (!Files.isDirectory(root) || !Files.exists(root) || isEmpty(root)) return 0;
if (config.get().maxAge > 0) { // delete files older that configured
final long now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
try(Stream<Path> stream = Files.list(root)) { if (config.get().maxAge > 0) { // delete files older that configured
deletedFiles += stream final long now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
.filter(Utilities::isValidBackup)// We check if we can get file's creation date so that the next line won't throw an exception
.filter(f -> now - Utilities.getFileCreationTime(f).get().toEpochSecond(ZoneOffset.UTC) > config.get().maxAge)
.mapToInt(f -> deleteFile(f, ctx))
.sum();
} catch (IOException e) {
log.error("An exception occurred while trying to delete old files!", e);
}
}
final int noToKeep = config.get().backupsToKeep > 0 ? config.get().backupsToKeep : Integer.MAX_VALUE; deletedFiles += RestoreableFile.applyOnFiles(root, 0,
final long maxSize = config.get().maxSize > 0 ? config.get().maxSize * 1024: Long.MAX_VALUE; e -> log.error("An exception occurred while trying to delete old files!", e),
stream -> stream.filter(f -> now - f.getCreationTime().toEpochSecond(ZoneOffset.UTC) > config.get().maxAge)
.mapToInt(f -> deleteFile(f.getFile(), ctx))
.sum()
);
}
AtomicInteger currentNo = new AtomicInteger(countBackups(root)); final int noToKeep = config.get().backupsToKeep > 0 ? config.get().backupsToKeep : Integer.MAX_VALUE;
AtomicLong currentSize = new AtomicLong(countSize(root)); final long maxSize = config.get().maxSize > 0 ? config.get().maxSize * 1024: Long.MAX_VALUE;
try(Stream<Path> stream = Files.list(root)) { long[] counts = count(root);
deletedFiles += stream
.filter(Utilities::isValidBackup) AtomicInteger currentNo = new AtomicInteger((int) counts[0]);
.sorted(Comparator.comparing(f -> Utilities.getFileCreationTime(f).get())) AtomicLong currentSize = new AtomicLong(counts[1]);
deletedFiles += RestoreableFile.applyOnFiles(root, 0,
e -> log.error("An exception occurred while trying to delete old files!", e),
stream -> stream.sequential()
.takeWhile(f -> (currentNo.get() > noToKeep) || (currentSize.get() > maxSize)) .takeWhile(f -> (currentNo.get() > noToKeep) || (currentSize.get() > maxSize))
.map(RestoreableFile::getFile)
.peek(f -> { .peek(f -> {
currentNo.decrementAndGet();
try { try {
currentSize.addAndGet(-Files.size(f)); currentSize.addAndGet(-Files.size(f));
} catch (IOException e) { } catch (IOException e) {
currentSize.set(0); currentSize.set(0);
return;
} }
currentNo.decrementAndGet();
}) })
.mapToInt(f -> deleteFile(f, ctx)) .mapToInt(f -> deleteFile(f, ctx))
.sum(); .sum());
} catch (IOException e) {
log.error("An exception occurred while trying to delete old files!", e);
}
}
return deletedFiles; return deletedFiles;
} }
private static int countBackups(Path path) { private static long[] count(Path root) {
try(Stream<Path> stream = Files.list(path)) { long n = 0, size = 0;
return (int) stream
.filter(Utilities::isValidBackup)
.count();
} catch (IOException e) {
log.error("Error while counting files!", e);
}
return 0;
}
private static long countSize(Path path) { try(Stream<Path> stream = Files.list(root)) {
try(Stream<Path> stream = Files.list(path)) { var it = stream.flatMap(f -> RestoreableFile.build(f).stream()).iterator();
return stream while(it.hasNext()) {
.filter(Utilities::isValidBackup) var f = it.next();
.mapToLong(f -> { try {
try { size += Files.size(f.getFile());
return Files.size(f); } catch (IOException e) {
} catch (IOException e) { log.error("Couldn't get size of " + f.getFile(), e);
log.error("Couldn't delete a file!", e); continue;
return 0; }
} n++;
})
.sum();
} catch (IOException e) {
log.error("Error while counting files!", e);
}
return 0;
}
private static boolean isEmpty(Path path) {
if (Files.isDirectory(path)) {
try (Stream<Path> entries = Files.list(path)) {
return entries.findFirst().isEmpty();
} catch (IOException e) {
return false;
} }
} catch (IOException e) {
log.error("Error while counting files!", e);
} }
return false; return new long[]{n, size};
}
private static boolean isEmpty(Path root) {
if (!Files.isDirectory(root)) return false;
return RestoreableFile.applyOnFiles(root, false, e -> {}, s -> s.findFirst().isEmpty());
} }
//1 -> ok, 0 -> err //1 -> ok, 0 -> err
private static int deleteFile(Path f, ServerCommandSource ctx) { private static int deleteFile(Path f, ServerCommandSource ctx) {
if(Globals.INSTANCE.getLockedFile().filter(p -> p == f).isEmpty()) { if(Globals.INSTANCE.getLockedFile().filter(p -> p == f).isPresent()) return 0;
try { try {
Files.delete(f); Files.delete(f);
log.sendInfoAL(ctx, "Deleting: {}", f); log.sendInfoAL(ctx, "Deleted: {}", f);
} catch (IOException e) { } catch (IOException e) {
if(Utilities.wasSentByPlayer(ctx)) log.sendError(ctx, "Something went wrong while deleting: {}.", f); if(Utilities.wasSentByPlayer(ctx)) log.sendError(ctx, "Something went wrong while deleting: {}.", f);
log.error("Something went wrong while deleting: {}.", f, e); log.error("Something went wrong while deleting: {}.", f, e);
return 0; return 0;
}
return 1;
} }
return 1;
return 0;
} }
} }

View File

@ -0,0 +1,118 @@
/*
* A simple backup mod for Fabric
* Copyright (C) 2022 Szum123321
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
package net.szum123321.textile_backup.core;
import net.szum123321.textile_backup.Globals;
import net.szum123321.textile_backup.config.ConfigPOJO;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
public class RestoreableFile implements Comparable<RestoreableFile> {
private final Path file;
private final ConfigPOJO.ArchiveFormat archiveFormat;
private final LocalDateTime creationTime;
private final String comment;
private RestoreableFile(Path file, ConfigPOJO.ArchiveFormat archiveFormat, LocalDateTime creationTime, String comment) {
this.file = file;
this.archiveFormat = archiveFormat;
this.creationTime = creationTime;
this.comment = comment;
}
public static <T> T applyOnFiles(Path root, T def, Consumer<IOException> errorConsumer, Function<Stream<RestoreableFile>, T> streamConsumer) {
try (Stream<Path> stream = Files.list(root)) {
return streamConsumer.apply(stream.flatMap(f -> RestoreableFile.build(f).stream()));
} catch (IOException e) {
errorConsumer.accept(e);
}
return def;
}
public static Optional<RestoreableFile> build(Path file) throws NoSuchElementException {
if(!Files.exists(file) || !Files.isRegularFile(file)) return Optional.empty();
String filename = file.getFileName().toString();
var format = Arrays.stream(ConfigPOJO.ArchiveFormat.values())
.filter(f -> filename.endsWith(f.getCompleteString()))
.findAny()
.orElse(null);
if(Objects.isNull(format)) return Optional.empty();
int parsed_pos = filename.length() - format.getCompleteString().length();
String comment = null;
if(filename.contains("#")) {
comment = filename.substring(filename.indexOf("#"), parsed_pos);
parsed_pos -= comment.length() - 1;
}
var time_string = filename.substring(0, parsed_pos);
try {
return Optional.of(new RestoreableFile(file, format, LocalDateTime.from(Utilities.getDateTimeFormatter().parse(time_string)), comment));
} catch (Exception ignored) {}
try {
return Optional.of(new RestoreableFile(file, format, LocalDateTime.from(Globals.defaultDateTimeFormatter.parse(time_string)), comment));
} catch (Exception ignored) {}
try {
FileTime fileTime = Files.readAttributes(file, BasicFileAttributes.class, NOFOLLOW_LINKS).creationTime();
return Optional.of(new RestoreableFile(file, format, LocalDateTime.ofInstant(fileTime.toInstant(), ZoneOffset.systemDefault()), comment));
} catch (IOException ignored) {}
return Optional.empty();
}
public Path getFile() { return file; }
public ConfigPOJO.ArchiveFormat getArchiveFormat() { return archiveFormat; }
public LocalDateTime getCreationTime() { return creationTime; }
public String getComment() { return comment; }
@Override
public int compareTo(@NotNull RestoreableFile o) { return creationTime.compareTo(o.creationTime); }
public String toString() {
return this.getCreationTime().format(Globals.defaultDateTimeFormatter) + (comment != null ? "#" + comment : "");
}
}

View File

@ -25,11 +25,9 @@ import net.minecraft.text.MutableText;
import net.minecraft.text.Text; import net.minecraft.text.Text;
import net.minecraft.util.Formatting; import net.minecraft.util.Formatting;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.szum123321.textile_backup.Globals;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.TextileBackup;
import net.szum123321.textile_backup.TextileLogger; import net.szum123321.textile_backup.TextileLogger;
import net.szum123321.textile_backup.config.ConfigHelper; import net.szum123321.textile_backup.config.ConfigHelper;
import net.szum123321.textile_backup.config.ConfigPOJO;
import net.szum123321.textile_backup.mixin.MinecraftServerSessionAccessor; import net.szum123321.textile_backup.mixin.MinecraftServerSessionAccessor;
import org.apache.commons.io.file.SimplePathVisitor; import org.apache.commons.io.file.SimplePathVisitor;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -40,13 +38,8 @@ import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.*; import java.time.*;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Optional;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
public class Utilities { public class Utilities {
private final static ConfigHelper config = ConfigHelper.INSTANCE; private final static ConfigHelper config = ConfigHelper.INSTANCE;
@ -73,19 +66,6 @@ public class Utilities {
.getWorldDirectory(World.OVERWORLD); .getWorldDirectory(World.OVERWORLD);
} }
public static Path getBackupRootPath(String worldName) {
Path path = Path.of(config.get().backupDirectoryPath).toAbsolutePath();
if (config.get().perWorldBackup) path = path.resolve(worldName);
try {
Files.createDirectories(path);
} catch (IOException e) {
//I REALLY shouldn't be handling this here
}
return path;
}
public static void deleteDirectory(Path path) throws IOException { public static void deleteDirectory(Path path) throws IOException {
Files.walkFileTree(path, new SimplePathVisitor() { Files.walkFileTree(path, new SimplePathVisitor() {
@ -121,6 +101,20 @@ public class Utilities {
return System.getProperty("os.name").toLowerCase().contains("win"); return System.getProperty("os.name").toLowerCase().contains("win");
} }
public static Path getBackupRootPath(String worldName) {
Path path = Path.of(config.get().backupDirectoryPath).toAbsolutePath();
if (config.get().perWorldBackup) path = path.resolve(worldName);
try {
Files.createDirectories(path);
} catch (IOException e) {
//I REALLY shouldn't be handling this here
}
return path;
}
public static boolean isBlacklisted(Path path) { public static boolean isBlacklisted(Path path) {
if(isWindows()) { //hotfix! if(isWindows()) { //hotfix!
if (path.getFileName().toString().equals("session.lock")) return true; if (path.getFileName().toString().equals("session.lock")) return true;
@ -129,58 +123,6 @@ public class Utilities {
return config.get().fileBlacklist.stream().anyMatch(path::startsWith); return config.get().fileBlacklist.stream().anyMatch(path::startsWith);
} }
public static Optional<ConfigPOJO.ArchiveFormat> getArchiveExtension(String fileName) {
String[] parts = fileName.split("\\.");
return Arrays.stream(ConfigPOJO.ArchiveFormat.values())
.filter(format -> format.getLastPiece().equals(parts[parts.length - 1]))
.findAny();
}
public static Optional<ConfigPOJO.ArchiveFormat> getArchiveExtension(Path f) {
return getArchiveExtension(f.getFileName().toString());
}
public static Optional<LocalDateTime> getFileCreationTime(Path file) {
if(getArchiveExtension(file).isEmpty()) return Optional.empty();
try {
FileTime fileTime = Files.readAttributes(file, BasicFileAttributes.class, NOFOLLOW_LINKS).creationTime();
return Optional.of(LocalDateTime.ofInstant(fileTime.toInstant(), ZoneOffset.systemDefault()));
} catch (IOException ignored) {}
String fileExtension = getArchiveExtension(file).get().getCompleteString();
try {
return Optional.of(
LocalDateTime.from(
Utilities.getDateTimeFormatter().parse(
file.getFileName().toString().split(fileExtension)[0].split("#")[0]
)));
} catch (Exception ignored) {}
try {
return Optional.of(
LocalDateTime.from(
Globals.defaultDateTimeFormatter.parse(
file.getFileName().toString().split(fileExtension)[0].split("#")[0]
)));
} catch (Exception ignored) {}
return Optional.empty();
}
public static boolean isValidBackup(Path f) {
return getArchiveExtension(f).isPresent() && getFileCreationTime(f).isPresent() && isFileOk(f);
}
public static boolean isFileOk(File f) {
return f.exists() && f.isFile();
}
public static boolean isFileOk(Path f) {
return Files.exists(f) && Files.isRegularFile(f);
}
public static DateTimeFormatter getDateTimeFormatter() { public static DateTimeFormatter getDateTimeFormatter() {
return DateTimeFormatter.ofPattern(config.get().dateTimeFormat); return DateTimeFormatter.ofPattern(config.get().dateTimeFormat);
} }

View File

@ -22,16 +22,17 @@ import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.command.ServerCommandSource;
import net.szum123321.textile_backup.core.ActionInitiator; import net.szum123321.textile_backup.core.ActionInitiator;
import net.szum123321.textile_backup.core.RestoreableFile;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public record RestoreContext(RestoreHelper.RestoreableFile restoreableFile, public record RestoreContext(RestoreableFile restoreableFile,
MinecraftServer server, MinecraftServer server,
@Nullable String comment, @Nullable String comment,
ActionInitiator initiator, ActionInitiator initiator,
ServerCommandSource commandSource) { ServerCommandSource commandSource) {
public static final class Builder { public static final class Builder {
private RestoreHelper.RestoreableFile file; private RestoreableFile file;
private MinecraftServer server; private MinecraftServer server;
private String comment; private String comment;
private ServerCommandSource serverCommandSource; private ServerCommandSource serverCommandSource;
@ -43,7 +44,7 @@ public record RestoreContext(RestoreHelper.RestoreableFile restoreableFile,
return new Builder(); return new Builder();
} }
public Builder setFile(RestoreHelper.RestoreableFile file) { public Builder setFile(RestoreableFile file) {
this.file = file; this.file = file;
return this; return this;
} }

View File

@ -23,18 +23,14 @@ import net.szum123321.textile_backup.Globals;
import net.szum123321.textile_backup.TextileBackup; import net.szum123321.textile_backup.TextileBackup;
import net.szum123321.textile_backup.TextileLogger; import net.szum123321.textile_backup.TextileLogger;
import net.szum123321.textile_backup.config.ConfigHelper; import net.szum123321.textile_backup.config.ConfigHelper;
import net.szum123321.textile_backup.config.ConfigPOJO;
import net.szum123321.textile_backup.core.ActionInitiator; import net.szum123321.textile_backup.core.ActionInitiator;
import net.szum123321.textile_backup.core.RestoreableFile;
import net.szum123321.textile_backup.core.Utilities; import net.szum123321.textile_backup.core.Utilities;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RestoreHelper { public class RestoreHelper {
private final static TextileLogger log = new TextileLogger(TextileBackup.MOD_NAME); private final static TextileLogger log = new TextileLogger(TextileBackup.MOD_NAME);
@ -43,16 +39,11 @@ public class RestoreHelper {
public static Optional<RestoreableFile> findFileAndLockIfPresent(LocalDateTime backupTime, MinecraftServer server) { public static Optional<RestoreableFile> findFileAndLockIfPresent(LocalDateTime backupTime, MinecraftServer server) {
Path root = Utilities.getBackupRootPath(Utilities.getLevelName(server)); Path root = Utilities.getBackupRootPath(Utilities.getLevelName(server));
Optional<RestoreableFile> optionalFile; Optional<RestoreableFile> optionalFile =
try (Stream<Path> stream = Files.list(root)) { RestoreableFile.applyOnFiles(root, Optional.empty(),
optionalFile = stream e -> log.error("An error occurred while trying to lock file!", e),
.map(RestoreableFile::newInstance) s -> s.filter(rf -> rf.getCreationTime().equals(backupTime))
.flatMap(Optional::stream) .findFirst());
.filter(rf -> rf.getCreationTime().equals(backupTime))
.findFirst();
} catch (IOException e) {
throw new RuntimeException(e);
}
optionalFile.ifPresent(r -> Globals.INSTANCE.setLockedFile(r.getFile())); optionalFile.ifPresent(r -> Globals.INSTANCE.setLockedFile(r.getFile()));
@ -79,66 +70,8 @@ public class RestoreHelper {
public static List<RestoreableFile> getAvailableBackups(MinecraftServer server) { public static List<RestoreableFile> getAvailableBackups(MinecraftServer server) {
Path root = Utilities.getBackupRootPath(Utilities.getLevelName(server)); Path root = Utilities.getBackupRootPath(Utilities.getLevelName(server));
try (Stream<Path> stream = Files.list(root)) { return RestoreableFile.applyOnFiles(root, List.of(),
return stream.filter(Utilities::isValidBackup) e -> log.error("Error while listing available backups", e),
.map(RestoreableFile::newInstance) s -> s.collect(Collectors.toList()));
.flatMap(Optional::stream)
.collect(Collectors.toList());
} catch (IOException e) {
log.error("Error while listing available backups", e);
return new LinkedList<>();
}
}
public static class RestoreableFile implements Comparable<RestoreableFile> {
private final Path file;
private final ConfigPOJO.ArchiveFormat archiveFormat;
private final LocalDateTime creationTime;
private final String comment;
private RestoreableFile(Path file) throws NoSuchElementException {
this.file = file;
archiveFormat = Utilities.getArchiveExtension(file).orElseThrow(() -> new NoSuchElementException("Couldn't get file extension!"));
String extension = archiveFormat.getCompleteString();
creationTime = Utilities.getFileCreationTime(file).orElseThrow(() -> new NoSuchElementException("Couldn't get file creation time!"));
final String filename = file.getFileName().toString();
if(filename.split("#").length > 1) this.comment = filename.split("#")[1].split(extension)[0];
else this.comment = null;
}
public static Optional<RestoreableFile> newInstance(Path file) {
try {
return Optional.of(new RestoreableFile(file));
} catch (NoSuchElementException ignored) {}
return Optional.empty();
}
public Path getFile() {
return file;
}
public ConfigPOJO.ArchiveFormat getArchiveFormat() {
return archiveFormat;
}
public LocalDateTime getCreationTime() {
return creationTime;
}
public String getComment() {
return comment;
}
@Override
public int compareTo(@NotNull RestoreHelper.RestoreableFile o) {
return creationTime.compareTo(o.creationTime);
}
public String toString() {
return this.getCreationTime().format(Globals.defaultDateTimeFormatter) + (comment != null ? "#" + comment : "");
}
} }
} }