| 1 | package net.minecraft.util.filefix;
|
| 2 |
|
| 3 | import com.google.common.annotations.VisibleForTesting;
|
| 4 | import com.google.gson.Gson;
|
| 5 | import com.google.gson.JsonElement;
|
| 6 | import com.google.gson.JsonObject;
|
| 7 | import com.mojang.datafixers.DataFixerBuilder;
|
| 8 | import com.mojang.datafixers.DataFixerBuilder.Result;
|
| 9 | import com.mojang.datafixers.schemas.Schema;
|
| 10 | import com.mojang.logging.LogUtils;
|
| 11 | import com.mojang.serialization.Codec;
|
| 12 | import com.mojang.serialization.Dynamic;
|
| 13 | import com.mojang.serialization.JsonOps;
|
| 14 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 15 | import java.io.IOException;
|
| 16 | import java.io.UncheckedIOException;
|
| 17 | import java.nio.file.AtomicMoveNotSupportedException;
|
| 18 | import java.nio.file.CopyOption;
|
| 19 | import java.nio.file.FileVisitResult;
|
| 20 | import java.nio.file.Files;
|
| 21 | import java.nio.file.Path;
|
| 22 | import java.nio.file.SimpleFileVisitor;
|
| 23 | import java.nio.file.StandardCopyOption;
|
| 24 | import java.nio.file.StandardOpenOption;
|
| 25 | import java.nio.file.attribute.BasicFileAttributes;
|
| 26 | import java.util.ArrayList;
|
| 27 | import java.util.List;
|
| 28 | import java.util.Locale;
|
| 29 | import java.util.UUID;
|
| 30 | import java.util.function.BiFunction;
|
| 31 | import net.minecraft.SharedConstants;
|
| 32 | import net.minecraft.nbt.CompoundTag;
|
| 33 | import net.minecraft.nbt.NbtAccounter;
|
| 34 | import net.minecraft.nbt.NbtIo;
|
| 35 | import net.minecraft.nbt.NbtOps;
|
| 36 | import net.minecraft.nbt.NbtUtils;
|
| 37 | import net.minecraft.util.FileUtil;
|
| 38 | import net.minecraft.util.datafix.DataFixTypes;
|
| 39 | import net.minecraft.util.filefix.virtualfilesystem.CopyOnWriteFileSystem;
|
| 40 | import net.minecraft.util.filefix.virtualfilesystem.FileMove;
|
| 41 | import net.minecraft.util.worldupdate.UpgradeProgress;
|
| 42 | import net.minecraft.world.level.storage.LevelResource;
|
| 43 | import net.minecraft.world.level.storage.LevelStorageSource;
|
| 44 | import net.minecraft.world.level.storage.PrimaryLevelData;
|
| 45 | import org.apache.commons.io.file.PathUtils;
|
| 46 | import org.apache.commons.lang3.mutable.MutableBoolean;
|
| 47 | import org.jspecify.annotations.Nullable;
|
| 48 | import org.slf4j.Logger;
|
| 49 |
|
| 50 | public class FileFixerUpper {
|
| 51 | private static final int FILE_FIXER_INTRODUCTION_VERSION = 4772;
|
| 52 | private static final Gson GSON = new Gson().newBuilder().setPrettyPrinting().create();
|
| 53 | private static final String FILE_FIX_DIRECTORY_NAME = "filefix";
|
| 54 | private static final String NEW_WORLD_TEMP_NAME = "new_world";
|
| 55 | private static final String UPGRADE_IN_PROGRESS_NAME = "upgrade_in_progress.json";
|
| 56 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 57 | private final Result dataFixer;
|
| 58 | private final List<FileFix> fileFixes;
|
| 59 | private final int latestFileFixerVersion;
|
| 60 |
|
| 61 | public FileFixerUpper(final Result dataFixer, final List<FileFix> fileFixes, final int latestFileFixerVersion) {
|
| 62 | this.dataFixer = dataFixer;
|
| 63 | this.fileFixes = List.copyOf(fileFixes);
|
| 64 | this.latestFileFixerVersion = latestFileFixerVersion;
|
| 65 | }
|
| 66 |
|
| 67 | public static int worldVersionToFileFixerVersion(final int levelDataVersion) {
|
| 68 | return levelDataVersion < 4772 ? 0 : levelDataVersion;
|
| 69 | }
|
| 70 |
|
| 71 | public boolean requiresFileFixing(final int levelDataVersion) {
|
| 72 | return worldVersionToFileFixerVersion(levelDataVersion) < this.latestFileFixerVersion;
|
| 73 | }
|
| 74 |
|
| 75 | public Dynamic<?> fix(final LevelStorageSource.LevelStorageAccess worldAccess, final Dynamic<?> levelDataTag, final UpgradeProgress upgradeProgress) throws FileFixException {
|
| 76 | return this.fix(worldAccess, levelDataTag, upgradeProgress, SharedConstants.getCurrentVersion().dataVersion().version());
|
| 77 | }
|
| 78 |
|
| 79 | @VisibleForTesting
|
| 80 | public Dynamic<?> fix(
|
| 81 | final LevelStorageSource.LevelStorageAccess worldAccess, Dynamic<?> levelDataTag, final UpgradeProgress upgradeProgress, final int toVersion
|
| 82 | ) throws FileFixException {
|
| 83 | int loadedVersion = NbtUtils.getDataVersion(levelDataTag);
|
| 84 | if (this.requiresFileFixing(loadedVersion)) {
|
| 85 | LOGGER.info("Starting upgrade for world \"{}\"", worldAccess.getLevelId());
|
| 86 | upgradeProgress.notifications().worldUpgradeStarted();
|
| 87 | Path worldFolder = worldAccess.getLevelDirectory().path();
|
| 88 | Path fileFixDirectory = worldFolder.resolve("filefix");
|
| 89 | Path tempWorld = fileFixDirectory.resolve("new_world");
|
| 90 |
|
| 91 | List<FileMove> moves;
|
| 92 | try {
|
| 93 | moves = this.startOrContinueFileFixing(upgradeProgress, toVersion, worldFolder, tempWorld, fileFixDirectory, loadedVersion);
|
| 94 | } catch (IOException e) {
|
| 95 | upgradeProgress.notifications().worldUpgradeFailed("The world upgrade failed during file fixing");
|
| 96 | throw new AbortedFileFixException(e);
|
| 97 | }
|
| 98 |
|
| 99 | try {
|
| 100 | swapInFixedWorld(worldAccess, moves, fileFixDirectory, tempWorld, upgradeProgress);
|
| 101 | } catch (AbortedFileFixException e) {
|
| 102 | if (e.notRevertedMoves().isEmpty()) {
|
| 103 | cleanup(fileFixDirectory);
|
| 104 | upgradeProgress.notifications().worldUpgradeFailed("The world upgrade failed while swapping in the file-fixed world");
|
| 105 | } else {
|
| 106 | upgradeProgress.notifications().worldUpgradeFailed("The world upgrade failed while swapping in the file-fixed world and some moves were not reverted");
|
| 107 | }
|
| 108 |
|
| 109 | throw e;
|
| 110 | }
|
| 111 |
|
| 112 | try {
|
| 113 | levelDataTag = worldAccess.getUnfixedDataTag(false);
|
| 114 | } catch (IOException e) {
|
| 115 | upgradeProgress.notifications().worldUpgradeFailed("The world upgrade failed while reading level.dat");
|
| 116 | throw new UncheckedIOException(e);
|
| 117 | }
|
| 118 |
|
| 119 | loadedVersion = NbtUtils.getDataVersion(levelDataTag);
|
| 120 | }
|
| 121 |
|
| 122 | Dynamic<?> fixedLevelDataTag = DataFixTypes.LEVEL.updateToCurrentVersion(this.dataFixer.fixer(), levelDataTag, loadedVersion);
|
| 123 | return addVersionsToLevelData(fixedLevelDataTag, toVersion);
|
| 124 | }
|
| 125 |
|
| 126 | private List<FileMove> startOrContinueFileFixing(
|
| 127 | final UpgradeProgress upgradeProgress,
|
| 128 | final int toVersion,
|
| 129 | final Path worldFolder,
|
| 130 | final Path tempWorld,
|
| 131 | final Path fileFixDirectory,
|
| 132 | final int loadedVersion
|
| 133 | ) throws IOException {
|
| 134 | Path upgradeInProgressFile = fileFixDirectory.resolve("upgrade_in_progress.json");
|
| 135 | List<FileMove> moves;
|
| 136 | if (Files.exists(upgradeInProgressFile)) {
|
| 137 | LOGGER.warn("Found previously interrupted world upgrade, attempting to continue it");
|
| 138 | moves = readMoves(worldFolder, tempWorld, upgradeInProgressFile);
|
| 139 | } else {
|
| 140 | if (Files.exists(fileFixDirectory)) {
|
| 141 | deleteDirectory(fileFixDirectory);
|
| 142 | }
|
| 143 |
|
| 144 | try {
|
| 145 | Files.createDirectory(fileFixDirectory);
|
| 146 | moves = this.applyFileFixersOnCow(upgradeProgress, loadedVersion, toVersion, worldFolder, fileFixDirectory, tempWorld);
|
| 147 | } catch (Exception e) {
|
| 148 | cleanup(fileFixDirectory);
|
| 149 | throw e;
|
| 150 | }
|
| 151 | }
|
| 152 |
|
| 153 | return moves;
|
| 154 | }
|
| 155 |
|
| 156 | private static void deleteDirectory(final Path directory) throws IOException {
|
| 157 | Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
|
| 158 | public FileVisitResult visitFile(final Path realPath, final BasicFileAttributes attrs) {
|
| 159 | try {
|
| 160 | Files.deleteIfExists(realPath);
|
| 161 | } catch (IOException var4) {
|
| 162 | }
|
| 163 |
|
| 164 | return FileVisitResult.CONTINUE;
|
| 165 | }
|
| 166 |
|
| 167 | public FileVisitResult postVisitDirectory(final Path realPath, final @Nullable IOException e) {
|
| 168 | try {
|
| 169 | Files.deleteIfExists(realPath);
|
| 170 | } catch (IOException var4) {
|
| 171 | }
|
| 172 |
|
| 173 | return FileVisitResult.CONTINUE;
|
| 174 | }
|
| 175 | });
|
| 176 | if (Files.exists(directory)) {
|
| 177 | PathUtils.deleteDirectory(directory);
|
| 178 | }
|
| 179 | }
|
| 180 |
|
| 181 | private static void cleanup(final Path fileFixDirectory) {
|
| 182 | try {
|
| 183 | deleteDirectory(fileFixDirectory);
|
| 184 | } catch (Exception ex) {
|
| 185 | LOGGER.error("Failed to clean up", ex);
|
| 186 | }
|
| 187 | }
|
| 188 |
|
| 189 | private List<FileMove> applyFileFixersOnCow(
|
| 190 | final UpgradeProgress upgradeProgress,
|
| 191 | final int loadedVersion,
|
| 192 | final int toVersion,
|
| 193 | final Path worldFolder,
|
| 194 | final Path fileFixDirectory,
|
| 195 | final Path tempWorld
|
| 196 | ) throws IOException {
|
| 197 | try (CopyOnWriteFileSystem fs = CopyOnWriteFileSystem.create(
|
| 198 | worldFolder.getFileName().toString(), worldFolder, fileFixDirectory.resolve("cow"), fileFixDirectory::equals
|
| 199 | )) {
|
| 200 | this.applyFileFixers(upgradeProgress, loadedVersion, toVersion, fs.rootPath());
|
| 201 | CopyOnWriteFileSystem.Moves moves = fs.collectMoveOperations(tempWorld);
|
| 202 | Files.createDirectory(tempWorld);
|
| 203 | CopyOnWriteFileSystem.createDirectories(moves.directories());
|
| 204 | CopyOnWriteFileSystem.moveFiles(moves.copiedFiles());
|
| 205 | return moves.preexistingFiles();
|
| 206 | }
|
| 207 | }
|
| 208 |
|
| 209 | @VisibleForTesting
|
| 210 | public void applyFileFixers(final UpgradeProgress upgradeProgress, final int loadedVersion, final int toVersion, final Path basePath) throws IOException {
|
| 211 | List<FileFix> applicableFixers = this.getApplicableFixers(loadedVersion, toVersion);
|
| 212 | upgradeProgress.setType(UpgradeProgress.Type.FILES);
|
| 213 | this.countFiles(applicableFixers, upgradeProgress);
|
| 214 | upgradeProgress.setStatus(UpgradeProgress.Status.UPGRADING);
|
| 215 | upgradeProgress.setApplicableFixerAmount(applicableFixers.size());
|
| 216 |
|
| 217 | for (FileFix fileFix : applicableFixers) {
|
| 218 | upgradeProgress.incrementRunningFileFixer();
|
| 219 | fileFix.runFixOperations(basePath, upgradeProgress);
|
| 220 | }
|
| 221 |
|
| 222 | this.writeUpdatedLevelData(basePath, toVersion);
|
| 223 | Files.deleteIfExists(basePath.resolve("level.dat_old"));
|
| 224 | Files.deleteIfExists(basePath.resolve("session.lock"));
|
| 225 | }
|
| 226 |
|
| 227 | private List<FileFix> getApplicableFixers(final int fromVersion, final int toVersion) {
|
| 228 | int fileFixerFromVersion = worldVersionToFileFixerVersion(fromVersion);
|
| 229 | return this.fileFixes.stream().filter(fileFix -> fileFix.getVersion() > fileFixerFromVersion && fileFix.getVersion() <= toVersion).toList();
|
| 230 | }
|
| 231 |
|
| 232 | private void countFiles(final List<FileFix> applicableFixers, final UpgradeProgress upgradeProgress) {
|
| 233 | upgradeProgress.setStatus(UpgradeProgress.Status.COUNTING);
|
| 234 | int totalFiles = 0;
|
| 235 |
|
| 236 | for (FileFix fileFix : applicableFixers) {
|
| 237 | totalFiles += fileFix.countFileOperations();
|
| 238 | }
|
| 239 |
|
| 240 | upgradeProgress.addTotalFileFixOperations(totalFiles);
|
| 241 | }
|
| 242 |
|
| 243 | private void writeUpdatedLevelData(final Path worldFolder, final int toVersion) throws IOException {
|
| 244 | Path levelDatPath = worldFolder.resolve(LevelResource.LEVEL_DATA_FILE.id());
|
| 245 | CompoundTag unfixedLevelDat = NbtIo.readCompressed(levelDatPath, NbtAccounter.defaultQuota());
|
| 246 | CompoundTag unfixedDataTag = unfixedLevelDat.getCompoundOrEmpty("Data");
|
| 247 | int dataVersion = NbtUtils.getDataVersion(unfixedDataTag);
|
| 248 | Dynamic<?> fixed = DataFixTypes.LEVEL.update(this.dataFixer.fixer(), new Dynamic<>(NbtOps.INSTANCE, unfixedDataTag), dataVersion, toVersion);
|
| 249 | fixed = addVersionsToLevelData(fixed, toVersion);
|
| 250 | Dynamic<?> dynamic = fixed.emptyMap().set("Data", fixed);
|
| 251 | NbtIo.writeCompressed((CompoundTag)dynamic.convert(NbtOps.INSTANCE).getValue(), levelDatPath);
|
| 252 | }
|
| 253 |
|
| 254 | private static Dynamic<?> addVersionsToLevelData(Dynamic<?> fixed, final int toVersion) {
|
| 255 | fixed = NbtUtils.addDataVersion(fixed, toVersion);
|
| 256 | fixed = PrimaryLevelData.writeLastPlayed(fixed);
|
| 257 | return PrimaryLevelData.writeVersionTag(fixed);
|
| 258 | }
|
| 259 |
|
| 260 | @VisibleForTesting
|
| 261 | protected static void swapInFixedWorld(
|
| 262 | final LevelStorageSource.LevelStorageAccess worldAccess,
|
| 263 | final List<FileMove> moves,
|
| 264 | final Path fileFixDirectory,
|
| 265 | final Path tempWorld,
|
| 266 | final UpgradeProgress upgradeProgress
|
| 267 | ) throws FileFixException {
|
| 268 | Path worldFolder = worldAccess.getLevelDirectory().path();
|
| 269 | Path savesDirectory = worldFolder.getParent();
|
| 270 | String worldName = worldFolder.getFileName().toString();
|
| 271 |
|
| 272 | Path tempWorldTopLevel;
|
| 273 | Path oldWorldFolder;
|
| 274 | FileSystemCapabilities fileSystemCapabilities;
|
| 275 | try {
|
| 276 | fileSystemCapabilities = detectFileSystemCapabilities(fileFixDirectory);
|
| 277 | tempWorldTopLevel = savesDirectory.resolve(FileUtil.findAvailableName(savesDirectory, worldName + " upgraded", ""));
|
| 278 | oldWorldFolder = savesDirectory.resolve(FileUtil.findAvailableName(savesDirectory, worldName + " OUTDATED", ""));
|
| 279 | } catch (Exception e) {
|
| 280 | throw new AbortedFileFixException(e);
|
| 281 | }
|
| 282 |
|
| 283 | if (!fileSystemCapabilities.atomicMove()) {
|
| 284 | throw new AtomicMoveNotSupportedFileFixException(fileSystemCapabilities);
|
| 285 | }
|
| 286 |
|
| 287 | CopyOption[] moveOptions = fileSystemCapabilities.getMoveOptions();
|
| 288 | LOGGER.info("File system capabilities: {}", fileSystemCapabilities);
|
| 289 | Path movesFile = fileFixDirectory.resolve("upgrade_in_progress.json");
|
| 290 |
|
| 291 | try {
|
| 292 | if (fileSystemCapabilities.hardLinks()) {
|
| 293 | CopyOnWriteFileSystem.hardLinkFiles(moves);
|
| 294 | } else {
|
| 295 | writeMoves(moves, worldFolder, tempWorld, movesFile);
|
| 296 | }
|
| 297 | } catch (Exception e) {
|
| 298 | throw new AbortedFileFixException(e, List.of(), fileSystemCapabilities);
|
| 299 | }
|
| 300 |
|
| 301 | LOGGER.info("Applying file structure changes for world \"{}\"", worldAccess.getLevelId());
|
| 302 | if (fileSystemCapabilities.hardLinks()) {
|
| 303 | try {
|
| 304 | LOGGER.info("Moving new hardlinked world to top level");
|
| 305 | Files.move(tempWorld, tempWorldTopLevel, moveOptions);
|
| 306 | } catch (Exception e) {
|
| 307 | LOGGER.error("Encountered error trying to move world folder:", e);
|
| 308 | throw new AbortedFileFixException(e, List.of(), fileSystemCapabilities);
|
| 309 | }
|
| 310 | } else {
|
| 311 | try {
|
| 312 | LOGGER.info("Moving files into new file structure");
|
| 313 | CopyOnWriteFileSystem.moveFilesWithRetry(moves, moveOptions);
|
| 314 | LOGGER.info("Moving new world to top level");
|
| 315 | Files.move(tempWorld, tempWorldTopLevel, moveOptions);
|
| 316 | } catch (Exception e) {
|
| 317 | LOGGER.error("Encountered error while trying to create new world folder:", e);
|
| 318 | List<FileMove> failedMoves = CopyOnWriteFileSystem.tryRevertMoves(moves, moveOptions);
|
| 319 | if (failedMoves.isEmpty()) {
|
| 320 | try {
|
| 321 | Files.deleteIfExists(movesFile);
|
| 322 | } catch (IOException e2) {
|
| 323 | LOGGER.warn("Failed to delete {}", movesFile, e);
|
| 324 | }
|
| 325 | }
|
| 326 |
|
| 327 | throw new AbortedFileFixException(e, failedMoves, fileSystemCapabilities);
|
| 328 | }
|
| 329 |
|
| 330 | LOGGER.info("Complete move");
|
| 331 |
|
| 332 | try {
|
| 333 | Files.deleteIfExists(movesFile);
|
| 334 | } catch (IOException e) {
|
| 335 | LOGGER.warn("Failed to delete {}", movesFile, e);
|
| 336 | }
|
| 337 | }
|
| 338 |
|
| 339 | LOGGER.info("Start cleanup");
|
| 340 |
|
| 341 | try {
|
| 342 | Files.deleteIfExists(worldFolder.resolve("level.dat"));
|
| 343 | Files.deleteIfExists(worldFolder.resolve("level.dat_old"));
|
| 344 | } catch (Exception e) {
|
| 345 | LOGGER.warn("Failed to delete outdated level.dat files: ", e);
|
| 346 | }
|
| 347 |
|
| 348 | MutableBoolean succeeded = new MutableBoolean();
|
| 349 |
|
| 350 | try {
|
| 351 | worldAccess.releaseTemporarilyAndRun(() -> {
|
| 352 | LOGGER.info("Moving out old world folder");
|
| 353 |
|
| 354 | try {
|
| 355 | Files.move(worldFolder, oldWorldFolder, moveOptions);
|
| 356 | } catch (Exception e) {
|
| 357 | LOGGER.warn("Failed to move outdated world folder out of the way; will try to delete instead: ", ex);
|
| 358 |
|
| 359 | try {
|
| 360 | deleteDirectory(worldFolder);
|
| 361 | } catch (Exception e2) {
|
| 362 | LOGGER.warn("Failed to delete outdated world folder: ", ex);
|
| 363 | throw new FailedCleanupFileFixException(ex, tempWorldTopLevel.getFileName().toString(), fileSystemCapabilities);
|
| 364 | }
|
| 365 | }
|
| 366 |
|
| 367 | LOGGER.info("Moving in new world folder");
|
| 368 |
|
| 369 | try {
|
| 370 | Files.move(tempWorldTopLevel, worldFolder, moveOptions);
|
| 371 | } catch (Exception e) {
|
| 372 | LOGGER.warn("Failed to move in new world folder: ", exx);
|
| 373 | throw new FailedCleanupFileFixException(exx, tempWorldTopLevel.getFileName().toString(), fileSystemCapabilities);
|
| 374 | }
|
| 375 |
|
| 376 | succeeded.setTrue();
|
| 377 | });
|
| 378 | } catch (IOException e) {
|
| 379 | Path newWorldFolder = succeeded.isTrue() ? worldFolder : tempWorldTopLevel;
|
| 380 | throw new FailedCleanupFileFixException(e, newWorldFolder.getFileName().toString(), fileSystemCapabilities);
|
| 381 | }
|
| 382 |
|
| 383 | LOGGER.info("Done applying file structure changes for world \"{}\". Cleaning up outdated data...", worldAccess.getLevelId());
|
| 384 |
|
| 385 | try {
|
| 386 | if (Files.exists(oldWorldFolder)) {
|
| 387 | deleteDirectory(oldWorldFolder);
|
| 388 | }
|
| 389 | } catch (Exception e) {
|
| 390 | LOGGER.warn("Failed to clean up old world folder", e);
|
| 391 | }
|
| 392 |
|
| 393 | LOGGER.info("Upgrade done for world \"{}\"", worldAccess.getLevelId());
|
| 394 | upgradeProgress.notifications().worldUpgradeFinished();
|
| 395 | }
|
| 396 |
|
| 397 | private static void writeMoves(final List<FileMove> moves, final Path fromDirectory, final Path toDirectory, final Path filePath) throws IOException {
|
| 398 | Codec<FileFixerUpper.UpgradeInProgress> codec = FileFixerUpper.UpgradeInProgress.codec(fromDirectory, toDirectory);
|
| 399 | JsonElement json = codec.encodeStart(JsonOps.INSTANCE, new FileFixerUpper.UpgradeInProgress(moves)).getOrThrow();
|
| 400 | Files.writeString(filePath, GSON.toJson(json), StandardOpenOption.DSYNC, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
|
| 401 | }
|
| 402 |
|
| 403 | private static List<FileMove> readMoves(final Path fromDirectory, final Path toDirectory, final Path filePath) throws IOException {
|
| 404 | JsonObject json = GSON.fromJson(Files.readString(filePath), JsonObject.class);
|
| 405 | Codec<FileFixerUpper.UpgradeInProgress> codec = FileFixerUpper.UpgradeInProgress.codec(fromDirectory, toDirectory);
|
| 406 | return codec.decode(JsonOps.INSTANCE, json).getOrThrow().getFirst().moves;
|
| 407 | }
|
| 408 |
|
| 409 | public static FileSystemCapabilities detectFileSystemCapabilities(final Path dir) throws IOException {
|
| 410 | return new FileSystemCapabilities(supportsAtomicMove(dir), supportsHardLinks(dir));
|
| 411 | }
|
| 412 |
|
| 413 | private static boolean supportsAtomicMove(final Path dir) throws IOException {
|
| 414 | Path sourceFile = dir.resolve(UUID.randomUUID().toString());
|
| 415 | Path targetFile = dir.resolve(UUID.randomUUID().toString());
|
| 416 |
|
| 417 | try {
|
| 418 | Files.createFile(sourceFile);
|
| 419 |
|
| 420 | try {
|
| 421 | Files.move(sourceFile, targetFile, StandardCopyOption.ATOMIC_MOVE);
|
| 422 | return true;
|
| 423 | } catch (AtomicMoveNotSupportedException var8) {
|
| 424 | return false;
|
| 425 | }
|
| 426 | } finally {
|
| 427 | Files.deleteIfExists(sourceFile);
|
| 428 | Files.deleteIfExists(targetFile);
|
| 429 | }
|
| 430 | }
|
| 431 |
|
| 432 | private static boolean supportsHardLinks(final Path dir) throws IOException {
|
| 433 | Path sourceFile = dir.resolve(UUID.randomUUID().toString());
|
| 434 | Path targetFile = dir.resolve(UUID.randomUUID().toString());
|
| 435 |
|
| 436 | try {
|
| 437 | Files.createFile(sourceFile);
|
| 438 |
|
| 439 | try {
|
| 440 | Files.createLink(targetFile, sourceFile);
|
| 441 | return true;
|
| 442 | } catch (Exception var8) {
|
| 443 | return false;
|
| 444 | }
|
| 445 | } finally {
|
| 446 | Files.deleteIfExists(sourceFile);
|
| 447 | Files.deleteIfExists(targetFile);
|
| 448 | }
|
| 449 | }
|
| 450 |
|
| 451 | public static class Builder {
|
| 452 | public final List<FileFix> fileFixes = new ArrayList<>();
|
| 453 | private final int currentVersion;
|
| 454 | private int latestFileFixerVersion;
|
| 455 | private final List<Schema> knownSchemas = new ArrayList<>();
|
| 456 |
|
| 457 | public Builder(final int currentVersion) {
|
| 458 | this.currentVersion = currentVersion;
|
| 459 | }
|
| 460 |
|
| 461 | public void addFixer(final FileFix fileFix) {
|
| 462 | if (!this.knownSchemas.contains(fileFix.getSchema())) {
|
| 463 | throw new IllegalArgumentException("Tried to add file fixer with unknown schema. Add it through FileFixerUpper#addSchema instead");
|
| 464 | }
|
| 465 |
|
| 466 | int fileFixVersion = fileFix.getVersion();
|
| 467 | if (fileFix.getVersion() > this.currentVersion) {
|
| 468 | throw new IllegalArgumentException(
|
| 469 | String.format(Locale.ROOT, "Tried to add too recent file fix for version: %s. The data version of the game is: %s", fileFixVersion, this.currentVersion)
|
| 470 | );
|
| 471 | }
|
| 472 |
|
| 473 | if (!this.fileFixes.isEmpty()) {
|
| 474 | FileFix last = this.fileFixes.getLast();
|
| 475 | if (last.getVersion() > fileFixVersion) {
|
| 476 | throw new IllegalArgumentException(
|
| 477 | String.format(Locale.ROOT, "Tried to add too recent file fix for version: %s. The most recent file fix version is %s", fileFixVersion, last.getVersion())
|
| 478 | );
|
| 479 | }
|
| 480 | }
|
| 481 |
|
| 482 | this.fileFixes.add(fileFix);
|
| 483 | }
|
| 484 |
|
| 485 | public Schema addSchema(final DataFixerBuilder fixerUpper, final int version, final BiFunction<Integer, Schema, Schema> factory) {
|
| 486 | this.latestFileFixerVersion = Math.max(version, this.latestFileFixerVersion);
|
| 487 | Schema schema = fixerUpper.addSchema(version, factory);
|
| 488 | this.knownSchemas.add(schema);
|
| 489 | return schema;
|
| 490 | }
|
| 491 |
|
| 492 | public FileFixerUpper build(final Result dataFixer) {
|
| 493 | return new FileFixerUpper(dataFixer, this.fileFixes, this.latestFileFixerVersion);
|
| 494 | }
|
| 495 | }
|
| 496 |
|
| 497 | public record UpgradeInProgress(List<FileMove> moves) {
|
| 498 | public static Codec<FileFixerUpper.UpgradeInProgress> codec(final Path fromDirectory, final Path toDirectory) {
|
| 499 | return RecordCodecBuilder.create(
|
| 500 | i -> i.group(FileMove.moveCodec(fromDirectory, toDirectory).listOf().fieldOf("moves").forGetter(FileFixerUpper.UpgradeInProgress::moves))
|
| 501 | .apply(i, FileFixerUpper.UpgradeInProgress::new)
|
| 502 | );
|
| 503 | }
|
| 504 | }
|
| 505 | }
|
| 506 |
|