| 1 | package net.minecraft.server.commands;
|
| 2 |
|
| 3 | import com.google.common.collect.Lists;
|
| 4 | import com.google.gson.JsonElement;
|
| 5 | import com.google.gson.JsonObject;
|
| 6 | import com.google.gson.stream.JsonWriter;
|
| 7 | import com.mojang.brigadier.CommandDispatcher;
|
| 8 | import com.mojang.brigadier.arguments.StringArgumentType;
|
| 9 | import com.mojang.brigadier.context.CommandContext;
|
| 10 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 11 | import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
|
| 12 | import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
|
| 13 | import com.mojang.brigadier.suggestion.SuggestionProvider;
|
| 14 | import com.mojang.logging.LogUtils;
|
| 15 | import com.mojang.serialization.DataResult;
|
| 16 | import com.mojang.serialization.JsonOps;
|
| 17 | import com.mojang.serialization.DataResult.Error;
|
| 18 | import java.io.BufferedWriter;
|
| 19 | import java.io.IOException;
|
| 20 | import java.nio.charset.StandardCharsets;
|
| 21 | import java.nio.file.Files;
|
| 22 | import java.nio.file.Path;
|
| 23 | import java.util.Collection;
|
| 24 | import java.util.List;
|
| 25 | import java.util.Optional;
|
| 26 | import java.util.stream.Collectors;
|
| 27 | import net.minecraft.SharedConstants;
|
| 28 | import net.minecraft.commands.CommandBuildContext;
|
| 29 | import net.minecraft.commands.CommandSourceStack;
|
| 30 | import net.minecraft.commands.Commands;
|
| 31 | import net.minecraft.commands.SharedSuggestionProvider;
|
| 32 | import net.minecraft.commands.arguments.ComponentArgument;
|
| 33 | import net.minecraft.network.chat.Component;
|
| 34 | import net.minecraft.network.chat.ComponentUtils;
|
| 35 | import net.minecraft.server.packs.PackType;
|
| 36 | import net.minecraft.server.packs.metadata.pack.PackMetadataSection;
|
| 37 | import net.minecraft.server.packs.repository.Pack;
|
| 38 | import net.minecraft.server.packs.repository.PackRepository;
|
| 39 | import net.minecraft.server.packs.repository.PackSource;
|
| 40 | import net.minecraft.util.FileUtil;
|
| 41 | import net.minecraft.util.GsonHelper;
|
| 42 | import net.minecraft.world.flag.FeatureFlagSet;
|
| 43 | import net.minecraft.world.flag.FeatureFlags;
|
| 44 | import net.minecraft.world.level.storage.LevelResource;
|
| 45 | import org.slf4j.Logger;
|
| 46 |
|
| 47 | public class DataPackCommand {
|
| 48 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 49 | private static final DynamicCommandExceptionType ERROR_UNKNOWN_PACK = new DynamicCommandExceptionType(
|
| 50 | id -> Component.translatableEscape("commands.datapack.unknown", id)
|
| 51 | );
|
| 52 | private static final DynamicCommandExceptionType ERROR_PACK_ALREADY_ENABLED = new DynamicCommandExceptionType(
|
| 53 | id -> Component.translatableEscape("commands.datapack.enable.failed", id)
|
| 54 | );
|
| 55 | private static final DynamicCommandExceptionType ERROR_PACK_ALREADY_DISABLED = new DynamicCommandExceptionType(
|
| 56 | id -> Component.translatableEscape("commands.datapack.disable.failed", id)
|
| 57 | );
|
| 58 | private static final DynamicCommandExceptionType ERROR_CANNOT_DISABLE_FEATURE = new DynamicCommandExceptionType(
|
| 59 | id -> Component.translatableEscape("commands.datapack.disable.failed.feature", id)
|
| 60 | );
|
| 61 | private static final Dynamic2CommandExceptionType ERROR_PACK_FEATURES_NOT_ENABLED = new Dynamic2CommandExceptionType(
|
| 62 | (id, flags) -> Component.translatableEscape("commands.datapack.enable.failed.no_flags", id, flags)
|
| 63 | );
|
| 64 | private static final DynamicCommandExceptionType ERROR_PACK_INVALID_NAME = new DynamicCommandExceptionType(
|
| 65 | id -> Component.translatableEscape("commands.datapack.create.invalid_name", id)
|
| 66 | );
|
| 67 | private static final DynamicCommandExceptionType ERROR_PACK_INVALID_FULL_NAME = new DynamicCommandExceptionType(
|
| 68 | id -> Component.translatableEscape("commands.datapack.create.invalid_full_name", id)
|
| 69 | );
|
| 70 | private static final DynamicCommandExceptionType ERROR_PACK_ALREADY_EXISTS = new DynamicCommandExceptionType(
|
| 71 | id -> Component.translatableEscape("commands.datapack.create.already_exists", id)
|
| 72 | );
|
| 73 | private static final Dynamic2CommandExceptionType ERROR_PACK_METADATA_ENCODE_FAILURE = new Dynamic2CommandExceptionType(
|
| 74 | (id, error) -> Component.translatableEscape("commands.datapack.create.metadata_encode_failure", id, error)
|
| 75 | );
|
| 76 | private static final DynamicCommandExceptionType ERROR_PACK_IO_FAILURE = new DynamicCommandExceptionType(
|
| 77 | id -> Component.translatableEscape("commands.datapack.create.io_failure", id)
|
| 78 | );
|
| 79 | private static final SuggestionProvider<CommandSourceStack> SELECTED_PACKS = (c, p) -> SharedSuggestionProvider.suggest(
|
| 80 | c.getSource().getServer().getPackRepository().getSelectedIds().stream().map(StringArgumentType::escapeIfRequired), p
|
| 81 | );
|
| 82 | private static final SuggestionProvider<CommandSourceStack> UNSELECTED_PACKS = (c, p) -> {
|
| 83 | PackRepository packRepository = c.getSource().getServer().getPackRepository();
|
| 84 | Collection<String> selectedIds = packRepository.getSelectedIds();
|
| 85 | FeatureFlagSet enabledFeatures = c.getSource().enabledFeatures();
|
| 86 | return SharedSuggestionProvider.suggest(
|
| 87 | packRepository.getAvailablePacks()
|
| 88 | .stream()
|
| 89 | .filter(pack -> pack.getRequestedFeatures().isSubsetOf(enabledFeatures))
|
| 90 | .map(Pack::getId)
|
| 91 | .filter(id -> !selectedIds.contains(id))
|
| 92 | .map(StringArgumentType::escapeIfRequired),
|
| 93 | p
|
| 94 | );
|
| 95 | };
|
| 96 |
|
| 97 | public static void register(final CommandDispatcher<CommandSourceStack> dispatcher, final CommandBuildContext context) {
|
| 98 | dispatcher.register(
|
| 99 | Commands.literal("datapack")
|
| 100 | .requires(Commands.hasPermission(Commands.LEVEL_GAMEMASTERS))
|
| 101 | .then(
|
| 102 | Commands.literal("enable")
|
| 103 | .then(
|
| 104 | Commands.argument("name", StringArgumentType.string())
|
| 105 | .suggests(UNSELECTED_PACKS)
|
| 106 | .executes(c -> enablePack(c.getSource(), getPack(c, "name", true), (l, p) -> p.getDefaultPosition().insert(l, p, Pack::selectionConfig, false)))
|
| 107 | .then(
|
| 108 | Commands.literal("after")
|
| 109 | .then(
|
| 110 | Commands.argument("existing", StringArgumentType.string())
|
| 111 | .suggests(SELECTED_PACKS)
|
| 112 | .executes(c -> enablePack(c.getSource(), getPack(c, "name", true), (l, p) -> l.add(l.indexOf(getPack(c, "existing", false)) + 1, p)))
|
| 113 | )
|
| 114 | )
|
| 115 | .then(
|
| 116 | Commands.literal("before")
|
| 117 | .then(
|
| 118 | Commands.argument("existing", StringArgumentType.string())
|
| 119 | .suggests(SELECTED_PACKS)
|
| 120 | .executes(c -> enablePack(c.getSource(), getPack(c, "name", true), (l, p) -> l.add(l.indexOf(getPack(c, "existing", false)), p)))
|
| 121 | )
|
| 122 | )
|
| 123 | .then(Commands.literal("last").executes(c -> enablePack(c.getSource(), getPack(c, "name", true), List::add)))
|
| 124 | .then(Commands.literal("first").executes(c -> enablePack(c.getSource(), getPack(c, "name", true), (l, p) -> l.add(0, p))))
|
| 125 | )
|
| 126 | )
|
| 127 | .then(
|
| 128 | Commands.literal("disable")
|
| 129 | .then(
|
| 130 | Commands.argument("name", StringArgumentType.string()).suggests(SELECTED_PACKS).executes(c -> disablePack(c.getSource(), getPack(c, "name", false)))
|
| 131 | )
|
| 132 | )
|
| 133 | .then(
|
| 134 | Commands.literal("list")
|
| 135 | .executes(c -> listPacks(c.getSource()))
|
| 136 | .then(Commands.literal("available").executes(c -> listAvailablePacks(c.getSource())))
|
| 137 | .then(Commands.literal("enabled").executes(c -> listEnabledPacks(c.getSource())))
|
| 138 | )
|
| 139 | .then(
|
| 140 | Commands.literal("create")
|
| 141 | .requires(Commands.hasPermission(Commands.LEVEL_OWNERS))
|
| 142 | .then(
|
| 143 | Commands.argument("id", StringArgumentType.string())
|
| 144 | .then(
|
| 145 | Commands.argument("description", ComponentArgument.textComponent(context))
|
| 146 | .executes(c -> createPack(c.getSource(), StringArgumentType.getString(c, "id"), ComponentArgument.getResolvedComponent(c, "description")))
|
| 147 | )
|
| 148 | )
|
| 149 | )
|
| 150 | );
|
| 151 | }
|
| 152 |
|
| 153 | private static int createPack(final CommandSourceStack source, final String id, final Component description) throws CommandSyntaxException {
|
| 154 | Path datapackDir = source.getServer().getWorldPath(LevelResource.DATAPACK_DIR);
|
| 155 | if (!FileUtil.isValidPathSegment(id)) {
|
| 156 | throw ERROR_PACK_INVALID_NAME.create(id);
|
| 157 | }
|
| 158 |
|
| 159 | if (!FileUtil.isPathPartPortable(id)) {
|
| 160 | throw ERROR_PACK_INVALID_FULL_NAME.create(id);
|
| 161 | }
|
| 162 |
|
| 163 | Path packDir = datapackDir.resolve(id);
|
| 164 | if (Files.exists(packDir)) {
|
| 165 | throw ERROR_PACK_ALREADY_EXISTS.create(id);
|
| 166 | }
|
| 167 |
|
| 168 | PackMetadataSection packMetadataSection = new PackMetadataSection(
|
| 169 | description, SharedConstants.getCurrentVersion().packVersion(PackType.SERVER_DATA).minorRange()
|
| 170 | );
|
| 171 | DataResult<JsonElement> encodedMeta = PackMetadataSection.SERVER_TYPE.codec().encodeStart(JsonOps.INSTANCE, packMetadataSection);
|
| 172 | Optional<Error<JsonElement>> error = encodedMeta.error();
|
| 173 | if (error.isPresent()) {
|
| 174 | throw ERROR_PACK_METADATA_ENCODE_FAILURE.create(id, error.get().message());
|
| 175 | }
|
| 176 |
|
| 177 | JsonObject topMcmeta = new JsonObject();
|
| 178 | topMcmeta.add(PackMetadataSection.SERVER_TYPE.name(), encodedMeta.getOrThrow());
|
| 179 |
|
| 180 | try {
|
| 181 | Files.createDirectory(packDir);
|
| 182 | Files.createDirectory(packDir.resolve(PackType.SERVER_DATA.getDirectory()));
|
| 183 |
|
| 184 | try (
|
| 185 | BufferedWriter mcmetaFile = Files.newBufferedWriter(packDir.resolve("pack.mcmeta"), StandardCharsets.UTF_8);
|
| 186 | JsonWriter jsonWriter = new JsonWriter(mcmetaFile);
|
| 187 | ) {
|
| 188 | jsonWriter.setSerializeNulls(false);
|
| 189 | jsonWriter.setIndent(" ");
|
| 190 | GsonHelper.writeValue(jsonWriter, topMcmeta, null);
|
| 191 | }
|
| 192 | } catch (IOException e) {
|
| 193 | LOGGER.warn("Failed to create pack at {}", datapackDir.toAbsolutePath(), e);
|
| 194 | throw ERROR_PACK_IO_FAILURE.create(id);
|
| 195 | }
|
| 196 |
|
| 197 | source.sendSuccess(() -> Component.translatable("commands.datapack.create.success", id), true);
|
| 198 | return 1;
|
| 199 | }
|
| 200 |
|
| 201 | private static int enablePack(final CommandSourceStack source, final Pack unopened, final DataPackCommand.Inserter inserter) throws CommandSyntaxException {
|
| 202 | PackRepository packRepository = source.getServer().getPackRepository();
|
| 203 | List<Pack> selected = Lists.newArrayList(packRepository.getSelectedPacks());
|
| 204 | inserter.apply(selected, unopened);
|
| 205 | source.sendSuccess(() -> Component.translatable("commands.datapack.modify.enable", unopened.getChatLink(true)), true);
|
| 206 | ReloadCommand.reloadPacks(selected.stream().map(Pack::getId).collect(Collectors.toList()), source);
|
| 207 | return selected.size();
|
| 208 | }
|
| 209 |
|
| 210 | private static int disablePack(final CommandSourceStack source, final Pack unopened) {
|
| 211 | PackRepository packRepository = source.getServer().getPackRepository();
|
| 212 | List<Pack> selected = Lists.newArrayList(packRepository.getSelectedPacks());
|
| 213 | selected.remove(unopened);
|
| 214 | source.sendSuccess(() -> Component.translatable("commands.datapack.modify.disable", unopened.getChatLink(true)), true);
|
| 215 | ReloadCommand.reloadPacks(selected.stream().map(Pack::getId).collect(Collectors.toList()), source);
|
| 216 | return selected.size();
|
| 217 | }
|
| 218 |
|
| 219 | private static int listPacks(final CommandSourceStack source) {
|
| 220 | return listEnabledPacks(source) + listAvailablePacks(source);
|
| 221 | }
|
| 222 |
|
| 223 | private static int listAvailablePacks(final CommandSourceStack source) {
|
| 224 | PackRepository repository = source.getServer().getPackRepository();
|
| 225 | repository.reload();
|
| 226 | Collection<Pack> selectedPacks = repository.getSelectedPacks();
|
| 227 | Collection<Pack> availablePacks = repository.getAvailablePacks();
|
| 228 | FeatureFlagSet enabledFeatures = source.enabledFeatures();
|
| 229 | List<Pack> unselectedPacks = availablePacks.stream().filter(p -> !selectedPacks.contains(p) && p.getRequestedFeatures().isSubsetOf(enabledFeatures)).toList();
|
| 230 | if (unselectedPacks.isEmpty()) {
|
| 231 | source.sendSuccess(() -> Component.translatable("commands.datapack.list.available.none"), false);
|
| 232 | } else {
|
| 233 | source.sendSuccess(
|
| 234 | () -> Component.translatable(
|
| 235 | "commands.datapack.list.available.success", unselectedPacks.size(), ComponentUtils.formatList(unselectedPacks, p -> p.getChatLink(false))
|
| 236 | ),
|
| 237 | false
|
| 238 | );
|
| 239 | }
|
| 240 |
|
| 241 | return unselectedPacks.size();
|
| 242 | }
|
| 243 |
|
| 244 | private static int listEnabledPacks(final CommandSourceStack source) {
|
| 245 | PackRepository repository = source.getServer().getPackRepository();
|
| 246 | repository.reload();
|
| 247 | Collection<? extends Pack> selectedPacks = repository.getSelectedPacks();
|
| 248 | if (selectedPacks.isEmpty()) {
|
| 249 | source.sendSuccess(() -> Component.translatable("commands.datapack.list.enabled.none"), false);
|
| 250 | } else {
|
| 251 | source.sendSuccess(
|
| 252 | () -> Component.translatable(
|
| 253 | "commands.datapack.list.enabled.success", selectedPacks.size(), ComponentUtils.formatList(selectedPacks, p -> p.getChatLink(true))
|
| 254 | ),
|
| 255 | false
|
| 256 | );
|
| 257 | }
|
| 258 |
|
| 259 | return selectedPacks.size();
|
| 260 | }
|
| 261 |
|
| 262 | private static Pack getPack(final CommandContext<CommandSourceStack> context, final String name, final boolean enabling) throws CommandSyntaxException {
|
| 263 | String id = StringArgumentType.getString(context, name);
|
| 264 | PackRepository repository = context.getSource().getServer().getPackRepository();
|
| 265 | Pack pack = repository.getPack(id);
|
| 266 | if (pack == null) {
|
| 267 | throw ERROR_UNKNOWN_PACK.create(id);
|
| 268 | } else {
|
| 269 | boolean enabled = repository.getSelectedPacks().contains(pack);
|
| 270 | if (enabling && enabled) {
|
| 271 | throw ERROR_PACK_ALREADY_ENABLED.create(id);
|
| 272 | } else if (!enabling && !enabled) {
|
| 273 | throw ERROR_PACK_ALREADY_DISABLED.create(id);
|
| 274 | } else {
|
| 275 | FeatureFlagSet availableFeatures = context.getSource().enabledFeatures();
|
| 276 | FeatureFlagSet requestedFeatures = pack.getRequestedFeatures();
|
| 277 | if (!enabling && !requestedFeatures.isEmpty() && pack.getPackSource() == PackSource.FEATURE) {
|
| 278 | throw ERROR_CANNOT_DISABLE_FEATURE.create(id);
|
| 279 | } else if (!requestedFeatures.isSubsetOf(availableFeatures)) {
|
| 280 | throw ERROR_PACK_FEATURES_NOT_ENABLED.create(id, FeatureFlags.printMissingFlags(availableFeatures, requestedFeatures));
|
| 281 | } else {
|
| 282 | return pack;
|
| 283 | }
|
| 284 | }
|
| 285 | }
|
| 286 | }
|
| 287 |
|
| 288 | private interface Inserter {
|
| 289 | void apply(final List<Pack> selected, final Pack pack) throws CommandSyntaxException;
|
| 290 | }
|
| 291 | }
|
| 292 |
|