| 1 | package net.minecraft.util.datafix.fixes;
|
| 2 |
|
| 3 | import com.google.gson.JsonElement;
|
| 4 | import com.mojang.datafixers.DataFix;
|
| 5 | import com.mojang.datafixers.TypeRewriteRule;
|
| 6 | import com.mojang.datafixers.schemas.Schema;
|
| 7 | import com.mojang.datafixers.types.Type;
|
| 8 | import com.mojang.datafixers.util.Pair;
|
| 9 | import com.mojang.logging.LogUtils;
|
| 10 | import com.mojang.serialization.Dynamic;
|
| 11 | import com.mojang.serialization.DynamicOps;
|
| 12 | import com.mojang.serialization.JsonOps;
|
| 13 | import net.minecraft.util.LenientJsonParser;
|
| 14 | import net.minecraft.util.Util;
|
| 15 | import org.slf4j.Logger;
|
| 16 |
|
| 17 | public class UnflattenTextComponentFix extends DataFix {
|
| 18 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 19 |
|
| 20 | public UnflattenTextComponentFix(final Schema outputSchema) {
|
| 21 | super(outputSchema, true);
|
| 22 | }
|
| 23 |
|
| 24 | @Override
|
| 25 | protected TypeRewriteRule makeRule() {
|
| 26 | Type<Pair<String, String>> textComponentType = (Type<Pair<String, String>>)this.getInputSchema().getType(References.TEXT_COMPONENT);
|
| 27 | Type<?> newTextComponentType = this.getOutputSchema().getType(References.TEXT_COMPONENT);
|
| 28 | return this.createFixer(textComponentType, newTextComponentType);
|
| 29 | }
|
| 30 |
|
| 31 | private <T> TypeRewriteRule createFixer(final Type<Pair<String, String>> textComponentType, final Type<T> newTextComponentType) {
|
| 32 | return this.fixTypeEverywhere(
|
| 33 | "UnflattenTextComponentFix",
|
| 34 | textComponentType,
|
| 35 | newTextComponentType,
|
| 36 | ops -> input -> Util.readTypedOrThrow(newTextComponentType, unflattenJson(ops, input.getSecond()), true).getValue()
|
| 37 | );
|
| 38 | }
|
| 39 |
|
| 40 | private static <T> Dynamic<T> unflattenJson(final DynamicOps<T> ops, final String jsonString) {
|
| 41 | try {
|
| 42 | JsonElement json = LenientJsonParser.parse(jsonString);
|
| 43 | if (!json.isJsonNull()) {
|
| 44 | return new Dynamic<>(ops, JsonOps.INSTANCE.convertTo(ops, json));
|
| 45 | }
|
| 46 | } catch (Exception e) {
|
| 47 | LOGGER.error("Failed to unflatten text component json: {}", jsonString, e);
|
| 48 | }
|
| 49 |
|
| 50 | return new Dynamic<>(ops, ops.createString(jsonString));
|
| 51 | }
|
| 52 | }
|
| 53 |
|