From dd18ce87ffd5a63dd2a833b3659454f8fede031f Mon Sep 17 00:00:00 2001 From: KnightMiner Date: Wed, 12 May 2021 20:49:23 -0400 Subject: [PATCH] Added command to dump all tags to a folder --- .../mantle/command/DumpAllTagsCommand.java | 147 ++++++++++++++++++ .../mantle/command/DumpTagCommand.java | 3 +- .../mantle/command/MantleCommand.java | 1 + .../mantle/command/TagCollectionArgument.java | 8 +- .../resources/assets/mantle/lang/en_us.json | 2 + 5 files changed, 158 insertions(+), 3 deletions(-) create mode 100644 src/main/java/slimeknights/mantle/command/DumpAllTagsCommand.java diff --git a/src/main/java/slimeknights/mantle/command/DumpAllTagsCommand.java b/src/main/java/slimeknights/mantle/command/DumpAllTagsCommand.java new file mode 100644 index 0000000..b49a8c1 --- /dev/null +++ b/src/main/java/slimeknights/mantle/command/DumpAllTagsCommand.java @@ -0,0 +1,147 @@ +package slimeknights.mantle.command; + +import com.google.common.collect.Maps; +import com.google.gson.JsonObject; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.command.CommandSource; +import net.minecraft.command.Commands; +import net.minecraft.resources.IResource; +import net.minecraft.resources.IResourceManager; +import net.minecraft.server.MinecraftServer; +import net.minecraft.tags.ITag.Builder; +import net.minecraft.util.JSONUtils; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.text.TranslationTextComponent; +import net.minecraftforge.common.ForgeTagHandler; +import net.minecraftforge.registries.ForgeRegistry; +import net.minecraftforge.registries.RegistryManager; +import org.apache.commons.io.IOUtils; +import slimeknights.mantle.Mantle; +import slimeknights.mantle.command.TagCollectionArgument.VanillaTagType; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.Map.Entry; + +import static slimeknights.mantle.command.DumpTagCommand.GSON; + +/** + * Dumps all tags to a folder + */ +public class DumpAllTagsCommand { + private static final String TAG_DUMP_PATH = "./mantle_data_dump"; + private static final int EXTENSION_LENGTH = ".json".length(); + + /** + * Registers this sub command with the root command + * @param subCommand Command builder + */ + public static void register(LiteralArgumentBuilder subCommand) { + subCommand.requires(sender -> sender.hasPermissionLevel(MantleCommand.PERMISSION_EDIT_SPAWN)) + .executes(DumpAllTagsCommand::runAll) + .then(Commands.argument("type", TagCollectionArgument.collection()) + .executes(DumpAllTagsCommand::runType)); + } + + /** Gets the path for the output */ + private static File getOutputFile(CommandContext context) { + return context.getSource().getServer().getFile(TAG_DUMP_PATH); + } + + /** Dumps all tags to the game directory */ + private static int runAll(CommandContext context) throws CommandSyntaxException { + File output = getOutputFile(context); + int tagsDumped = 0; + for (VanillaTagType type : VanillaTagType.values()) { + tagsDumped += runForFolder(context, type.getName(), type.getTagFolder(), output); + } + + for (ResourceLocation type : ForgeTagHandler.getCustomTagTypeNames()) { + ForgeRegistry registry = RegistryManager.ACTIVE.getRegistry(type); + if (registry != null && registry.getTagFolder() != null) { + tagsDumped += runForFolder(context, type, registry.getTagFolder(), output); + } + } + // print the output path + context.getSource().sendFeedback(new TranslationTextComponent("command.mantle.dump_all_tags.success", output.getAbsolutePath()), true); + return tagsDumped; + } + + /** Dumps a single type of tags to the game directory */ + private static int runType(CommandContext context) throws CommandSyntaxException { + File output = getOutputFile(context); + TagCollectionArgument.Result type = context.getArgument("type", TagCollectionArgument.Result.class); + int result = runForFolder(context, type.getName(), type.getTagFolder(), output); + // print result + context.getSource().sendFeedback(new TranslationTextComponent("command.mantle.dump_all_tags.type_success", type.getName(), output.getAbsolutePath()), true); + return result; + } + + /** + * Runs the view-tag command + * @param context Tag context + * @return Integer return + * @throws CommandSyntaxException If invalid values are passed + */ + private static int runForFolder(CommandContext context, ResourceLocation tagType, String tagFolder, File output) throws CommandSyntaxException { + Map foundTags = Maps.newHashMap(); + MinecraftServer server = context.getSource().getServer(); + IResourceManager manager = server.getDataPackRegistries().getResourceManager(); + + // iterate all tags from the datapack + String dataPackFolder = "tags/" + tagFolder; + for (ResourceLocation resourcePath : manager.getAllResourceLocations(dataPackFolder, fileName -> fileName.endsWith(".json"))) { + String path = resourcePath.getPath(); + ResourceLocation tagId = new ResourceLocation(resourcePath.getNamespace(), path.substring(dataPackFolder.length() + 1, path.length() - EXTENSION_LENGTH)); + try { + for (IResource resource : manager.getAllResources(resourcePath)) { + try ( + InputStream inputstream = resource.getInputStream(); + Reader reader = new BufferedReader(new InputStreamReader(inputstream, StandardCharsets.UTF_8)) + ) { + JsonObject json = JSONUtils.fromJson(GSON, reader, JsonObject.class); + if (json == null) { + Mantle.logger.error("Couldn't load {} tag list {} from {} in data pack {} as it is empty or null", tagType, tagId, resourcePath, resource.getPackName()); + } else { + // store by the resource path instead of the ID, thats the one we want at the end + foundTags.computeIfAbsent(resourcePath, id -> Builder.create()).deserialize(json, resource.getPackName()); + } + } catch (RuntimeException | IOException ex) { + Mantle.logger.error("Couldn't read {} tag list {} from {} in data pack {}", tagType, tagId, resourcePath, resource.getPackName(), ex); + } finally { + IOUtils.closeQuietly(resource); + } + } + } catch (IOException ex) { + Mantle.logger.error("Couldn't read {} tag list {} from {}", tagType, tagId, resourcePath, ex); + } + } + + // save all tags + for (Entry entry : foundTags.entrySet()) { + ResourceLocation location = entry.getKey(); + Path path = output.toPath().resolve(location.getNamespace() + "/" + location.getPath()); + try { + Files.createDirectories(path.getParent()); + try (BufferedWriter writer = Files.newBufferedWriter(path)) { + writer.write(GSON.toJson(entry.getValue().serialize())); + } + } catch (IOException ex) { + Mantle.logger.error("Couldn't save tags to {}", path, ex); + } + } + + return foundTags.size(); + } +} diff --git a/src/main/java/slimeknights/mantle/command/DumpTagCommand.java b/src/main/java/slimeknights/mantle/command/DumpTagCommand.java index 0547fee..90fc7cd 100644 --- a/src/main/java/slimeknights/mantle/command/DumpTagCommand.java +++ b/src/main/java/slimeknights/mantle/command/DumpTagCommand.java @@ -30,7 +30,7 @@ import java.util.List; /** Command that dumps a tag into a JSON object */ public class DumpTagCommand { - private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + protected static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private static final Dynamic2CommandExceptionType ERROR_READING_TAG = new Dynamic2CommandExceptionType((type, name) -> new TranslationTextComponent("command.mantle.dump_tag.read_error", type, name)); /** @@ -46,6 +46,7 @@ public class DumpTagCommand { /** * Runs the view-tag command + * * @param context Tag context * @return Integer return * @throws CommandSyntaxException If invalid values are passed diff --git a/src/main/java/slimeknights/mantle/command/MantleCommand.java b/src/main/java/slimeknights/mantle/command/MantleCommand.java index 9ec6364..b073312 100644 --- a/src/main/java/slimeknights/mantle/command/MantleCommand.java +++ b/src/main/java/slimeknights/mantle/command/MantleCommand.java @@ -46,6 +46,7 @@ public class MantleCommand { // sub commands register(builder, "view_tag", ViewTagCommand::register); register(builder, "dump_tag", DumpTagCommand::register); + register(builder, "dump_all_tags", DumpAllTagsCommand::register); register(builder, "tags_for", TagsForCommand::register); // register final command diff --git a/src/main/java/slimeknights/mantle/command/TagCollectionArgument.java b/src/main/java/slimeknights/mantle/command/TagCollectionArgument.java index 800b0b2..9251f66 100644 --- a/src/main/java/slimeknights/mantle/command/TagCollectionArgument.java +++ b/src/main/java/slimeknights/mantle/command/TagCollectionArgument.java @@ -49,7 +49,7 @@ public class TagCollectionArgument implements ArgumentType registry, ResourceLocation name) { for (VanillaTagType type : VanillaTagType.values()) { if (name.equals(type.getName())) { - return Result.of(name, name.getPath() + "s", registry, type.getCollection()); + return Result.of(name, type.getTagFolder(), registry, type.getCollection()); } } return null; @@ -98,7 +98,7 @@ public class TagCollectionArgument implements ArgumentType TagCollectionManager.getManager().getBlockTags()), ITEM(Registry.ITEM_KEY.getLocation(), () -> TagCollectionManager.getManager().getItemTags()), FLUID(Registry.FLUID_KEY.getLocation(), () -> TagCollectionManager.getManager().getFluidTags()), @@ -111,6 +111,10 @@ public class TagCollectionArgument implements ArgumentType getCollection() { return supplier.get(); } + + public String getTagFolder() { + return name.getPath() + "s"; + } } /** Iterator for all possible collection names */ diff --git a/src/main/resources/assets/mantle/lang/en_us.json b/src/main/resources/assets/mantle/lang/en_us.json index d1dc97d..5c6610b 100644 --- a/src/main/resources/assets/mantle/lang/en_us.json +++ b/src/main/resources/assets/mantle/lang/en_us.json @@ -15,6 +15,8 @@ "command.mantle.dump_tag.success": "Printed combined %s tag '%s' to console log", "command.mantle.dump_tag.read_error": "Error reading %s tag '%s':", + "command.mantle.dump_all_tags.success": "Dumped all tags to '%s'", + "command.mantle.dump_all_tags.type_success": "Dumped all %s tags to '%s'", "command.mantle.tags_for.success": "%s tags for '%s':",