| 1 | package net.minecraft.util.filefix.access;
|
| 2 |
|
| 3 | import com.mojang.logging.LogUtils;
|
| 4 | import com.mojang.serialization.Dynamic;
|
| 5 | import java.io.IOException;
|
| 6 | import java.nio.file.NoSuchFileException;
|
| 7 | import java.nio.file.Path;
|
| 8 | import java.util.Optional;
|
| 9 | import java.util.function.BiConsumer;
|
| 10 | import net.minecraft.nbt.CompoundTag;
|
| 11 | import net.minecraft.nbt.NbtAccounter;
|
| 12 | import net.minecraft.nbt.NbtIo;
|
| 13 | import net.minecraft.nbt.NbtOps;
|
| 14 | import net.minecraft.nbt.Tag;
|
| 15 | import net.minecraft.util.FileUtil;
|
| 16 | import org.slf4j.Logger;
|
| 17 |
|
| 18 | public abstract class CompressedNbt implements AutoCloseable {
|
| 19 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 20 | private final Path path;
|
| 21 | private final CompressedNbt.MissingSeverity missingSeverity;
|
| 22 |
|
| 23 | public CompressedNbt(final Path path, final CompressedNbt.MissingSeverity missingSeverity) {
|
| 24 | this.path = path;
|
| 25 | this.missingSeverity = missingSeverity;
|
| 26 | }
|
| 27 |
|
| 28 | public abstract Optional<Dynamic<Tag>> read() throws IOException;
|
| 29 |
|
| 30 | protected final Optional<Dynamic<Tag>> readFile() throws IOException {
|
| 31 | try {
|
| 32 | return Optional.of(new Dynamic<>(NbtOps.INSTANCE, NbtIo.readCompressed(this.path, NbtAccounter.unlimitedHeap())));
|
| 33 | } catch (NoSuchFileException ignored) {
|
| 34 | this.missingSeverity.log("Missing file: {}", this.path);
|
| 35 | return Optional.empty();
|
| 36 | }
|
| 37 | }
|
| 38 |
|
| 39 | public abstract <T> void write(final Dynamic<T> data);
|
| 40 |
|
| 41 | protected final <T> void writeFile(final Dynamic<T> data) {
|
| 42 | CompoundTag cast = (CompoundTag)data.cast(NbtOps.INSTANCE);
|
| 43 |
|
| 44 | try {
|
| 45 | FileUtil.createDirectoriesSafe(this.path.getParent());
|
| 46 | NbtIo.writeCompressed(cast, this.path);
|
| 47 | } catch (IOException e) {
|
| 48 | LOGGER.error("Failed to write to {}", this.path, e);
|
| 49 | }
|
| 50 | }
|
| 51 |
|
| 52 | public Path path() {
|
| 53 | return this.path;
|
| 54 | }
|
| 55 |
|
| 56 | @Override
|
| 57 | public void close() {
|
| 58 | }
|
| 59 |
|
| 60 | public enum MissingSeverity {
|
| 61 | IMPORTANT(CompressedNbt.LOGGER::error),
|
| 62 | NEUTRAL(CompressedNbt.LOGGER::info),
|
| 63 | MINOR(CompressedNbt.LOGGER::debug);
|
| 64 |
|
| 65 | private final BiConsumer<String, Object> logFunction;
|
| 66 |
|
| 67 | MissingSeverity(final BiConsumer<String, Object> logFunction) {
|
| 68 | this.logFunction = logFunction;
|
| 69 | }
|
| 70 |
|
| 71 | public void log(final String message, final Path path) {
|
| 72 | this.logFunction.accept(message, path);
|
| 73 | }
|
| 74 | }
|
| 75 | }
|
| 76 |
|