Refactor backup command.

This commit is contained in:
Logan Gorence
2021-12-20 23:28:00 +00:00
parent 10f6bf98dd
commit 9413211a82

View File

@ -9,7 +9,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant; import java.time.Instant;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
@ -69,12 +68,30 @@ public class BackupCommand implements CommandExecutor {
final var backupFile = backupPath.resolve( final var backupFile = backupPath.resolve(
String.format("backup-%s.zip", Instant.now().toString())).toFile(); String.format("backup-%s.zip", Instant.now().toString())).toFile();
final var zipFileStream = new FileOutputStream(backupFile); final var zipFileStream = new FileOutputStream(backupFile);
final var zipStream = new ZipOutputStream(new BufferedOutputStream(zipFileStream));
try (zipFileStream; var zipStream = new ZipOutputStream( try (zipFileStream; zipStream) {
new BufferedOutputStream(zipFileStream))) { backupPlugins(server, zipStream);
backupWorlds(server, zipStream);
} finally {
RUNNING.set(false);
server.sendMessage(Util.formatSystemMessage("Backup finished."));
}
}
private void backupPlugins(Server server, ZipOutputStream zipStream) {
try {
addDirectoryToZip(zipStream, server.getPluginsFolder().toPath());
} catch (IOException e) {
// TODO: Add error handling.
e.printStackTrace();
}
}
private void backupWorlds(Server server, ZipOutputStream zipStream) {
final var worlds = server.getWorlds(); final var worlds = server.getWorlds();
for (World world : worlds) { for (World world : worlds) {
final var worldPath = world.getWorldFolder().toPath().toString(); final var worldPath = world.getWorldFolder().toPath();
// Save the world. // Save the world.
world.save(); world.save();
@ -83,7 +100,19 @@ public class BackupCommand implements CommandExecutor {
world.setAutoSave(false); world.setAutoSave(false);
try { try {
final var paths = Files.walk(Paths.get(worldPath)) addDirectoryToZip(zipStream, worldPath);
} catch (IOException e) {
// TODO: Add error handling.
e.printStackTrace();
}
// Re-enable auto saving for this world.
world.setAutoSave(true);
}
}
private void addDirectoryToZip(ZipOutputStream zipStream, Path directoryPath) throws IOException {
final var paths = Files.walk(directoryPath)
.filter(Files::isRegularFile) .filter(Files::isRegularFile)
.toList(); .toList();
@ -98,16 +127,5 @@ public class BackupCommand implements CommandExecutor {
} }
} }
} }
} catch (IOException e) {
e.printStackTrace();
}
// Re-enable auto saving for this world.
world.setAutoSave(true);
}
} finally {
RUNNING.set(false);
server.sendMessage(Util.formatSystemMessage("Backup finished."));
}
} }
} }