| 1 | package net.minecraft.commands;
|
| 2 |
|
| 3 | import com.mojang.brigadier.CommandDispatcher;
|
| 4 | import com.mojang.brigadier.ParseResults;
|
| 5 | import com.mojang.brigadier.StringReader;
|
| 6 | import com.mojang.brigadier.arguments.ArgumentType;
|
| 7 | import com.mojang.brigadier.builder.ArgumentBuilder;
|
| 8 | import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
| 9 | import com.mojang.brigadier.builder.RequiredArgumentBuilder;
|
| 10 | import com.mojang.brigadier.context.CommandContextBuilder;
|
| 11 | import com.mojang.brigadier.context.ContextChain;
|
| 12 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 13 | import com.mojang.brigadier.suggestion.SuggestionProvider;
|
| 14 | import com.mojang.brigadier.tree.ArgumentCommandNode;
|
| 15 | import com.mojang.brigadier.tree.CommandNode;
|
| 16 | import com.mojang.brigadier.tree.RootCommandNode;
|
| 17 | import com.mojang.logging.LogUtils;
|
| 18 | import java.util.HashMap;
|
| 19 | import java.util.Map;
|
| 20 | import java.util.Optional;
|
| 21 | import java.util.Set;
|
| 22 | import java.util.function.Consumer;
|
| 23 | import java.util.function.Predicate;
|
| 24 | import java.util.function.UnaryOperator;
|
| 25 | import java.util.stream.Collectors;
|
| 26 | import java.util.stream.Stream;
|
| 27 | import net.minecraft.ChatFormatting;
|
| 28 | import net.minecraft.SharedConstants;
|
| 29 | import net.minecraft.commands.execution.ExecutionContext;
|
| 30 | import net.minecraft.commands.synchronization.ArgumentTypeInfos;
|
| 31 | import net.minecraft.commands.synchronization.ArgumentUtils;
|
| 32 | import net.minecraft.commands.synchronization.SuggestionProviders;
|
| 33 | import net.minecraft.core.HolderLookup;
|
| 34 | import net.minecraft.core.HolderSet;
|
| 35 | import net.minecraft.core.Registry;
|
| 36 | import net.minecraft.data.registries.VanillaRegistries;
|
| 37 | import net.minecraft.gametest.framework.TestCommand;
|
| 38 | import net.minecraft.network.chat.ClickEvent;
|
| 39 | import net.minecraft.network.chat.CommonComponents;
|
| 40 | import net.minecraft.network.chat.Component;
|
| 41 | import net.minecraft.network.chat.ComponentUtils;
|
| 42 | import net.minecraft.network.chat.HoverEvent;
|
| 43 | import net.minecraft.network.chat.MutableComponent;
|
| 44 | import net.minecraft.network.protocol.game.ClientboundCommandsPacket;
|
| 45 | import net.minecraft.resources.Identifier;
|
| 46 | import net.minecraft.resources.ResourceKey;
|
| 47 | import net.minecraft.server.commands.AdvancementCommands;
|
| 48 | import net.minecraft.server.commands.AttributeCommand;
|
| 49 | import net.minecraft.server.commands.BanIpCommands;
|
| 50 | import net.minecraft.server.commands.BanListCommands;
|
| 51 | import net.minecraft.server.commands.BanPlayerCommands;
|
| 52 | import net.minecraft.server.commands.BossBarCommands;
|
| 53 | import net.minecraft.server.commands.ChaseCommand;
|
| 54 | import net.minecraft.server.commands.ClearInventoryCommands;
|
| 55 | import net.minecraft.server.commands.CloneCommands;
|
| 56 | import net.minecraft.server.commands.ComputeCommand;
|
| 57 | import net.minecraft.server.commands.DamageCommand;
|
| 58 | import net.minecraft.server.commands.DataPackCommand;
|
| 59 | import net.minecraft.server.commands.DeOpCommands;
|
| 60 | import net.minecraft.server.commands.DebugCommand;
|
| 61 | import net.minecraft.server.commands.DebugConfigCommand;
|
| 62 | import net.minecraft.server.commands.DebugMobSpawningCommand;
|
| 63 | import net.minecraft.server.commands.DebugPathCommand;
|
| 64 | import net.minecraft.server.commands.DefaultGameModeCommands;
|
| 65 | import net.minecraft.server.commands.DialogCommand;
|
| 66 | import net.minecraft.server.commands.DifficultyCommand;
|
| 67 | import net.minecraft.server.commands.EffectCommands;
|
| 68 | import net.minecraft.server.commands.EmoteCommands;
|
| 69 | import net.minecraft.server.commands.EnchantCommand;
|
| 70 | import net.minecraft.server.commands.ExecuteCommand;
|
| 71 | import net.minecraft.server.commands.ExperienceCommand;
|
| 72 | import net.minecraft.server.commands.FetchProfileCommand;
|
| 73 | import net.minecraft.server.commands.FillBiomeCommand;
|
| 74 | import net.minecraft.server.commands.FillCommand;
|
| 75 | import net.minecraft.server.commands.ForceLoadCommand;
|
| 76 | import net.minecraft.server.commands.FunctionCommand;
|
| 77 | import net.minecraft.server.commands.GameModeCommand;
|
| 78 | import net.minecraft.server.commands.GameRuleCommand;
|
| 79 | import net.minecraft.server.commands.GiveCommand;
|
| 80 | import net.minecraft.server.commands.HelpCommand;
|
| 81 | import net.minecraft.server.commands.JfrCommand;
|
| 82 | import net.minecraft.server.commands.KickCommand;
|
| 83 | import net.minecraft.server.commands.KillCommand;
|
| 84 | import net.minecraft.server.commands.ListPlayersCommand;
|
| 85 | import net.minecraft.server.commands.LocateCommand;
|
| 86 | import net.minecraft.server.commands.LootCommand;
|
| 87 | import net.minecraft.server.commands.MsgCommand;
|
| 88 | import net.minecraft.server.commands.OpCommand;
|
| 89 | import net.minecraft.server.commands.PardonCommand;
|
| 90 | import net.minecraft.server.commands.PardonIpCommand;
|
| 91 | import net.minecraft.server.commands.ParticleCommand;
|
| 92 | import net.minecraft.server.commands.PerfCommand;
|
| 93 | import net.minecraft.server.commands.PlaceCommand;
|
| 94 | import net.minecraft.server.commands.PlaySoundCommand;
|
| 95 | import net.minecraft.server.commands.PostEffectCommand;
|
| 96 | import net.minecraft.server.commands.PublishCommand;
|
| 97 | import net.minecraft.server.commands.RaidCommand;
|
| 98 | import net.minecraft.server.commands.RandomCommand;
|
| 99 | import net.minecraft.server.commands.RecipeCommand;
|
| 100 | import net.minecraft.server.commands.ReloadCommand;
|
| 101 | import net.minecraft.server.commands.ReturnCommand;
|
| 102 | import net.minecraft.server.commands.RideCommand;
|
| 103 | import net.minecraft.server.commands.RotateCommand;
|
| 104 | import net.minecraft.server.commands.SaveAllCommand;
|
| 105 | import net.minecraft.server.commands.SaveOffCommand;
|
| 106 | import net.minecraft.server.commands.SaveOnCommand;
|
| 107 | import net.minecraft.server.commands.SayCommand;
|
| 108 | import net.minecraft.server.commands.ScheduleCommand;
|
| 109 | import net.minecraft.server.commands.ScoreboardCommand;
|
| 110 | import net.minecraft.server.commands.SeedCommand;
|
| 111 | import net.minecraft.server.commands.ServerPackCommand;
|
| 112 | import net.minecraft.server.commands.SetBlockCommand;
|
| 113 | import net.minecraft.server.commands.SetPlayerIdleTimeoutCommand;
|
| 114 | import net.minecraft.server.commands.SetSpawnCommand;
|
| 115 | import net.minecraft.server.commands.SetWorldSpawnCommand;
|
| 116 | import net.minecraft.server.commands.SpawnArmorTrimsCommand;
|
| 117 | import net.minecraft.server.commands.SpectateCommand;
|
| 118 | import net.minecraft.server.commands.SpreadPlayersCommand;
|
| 119 | import net.minecraft.server.commands.StopCommand;
|
| 120 | import net.minecraft.server.commands.StopSoundCommand;
|
| 121 | import net.minecraft.server.commands.StopwatchCommand;
|
| 122 | import net.minecraft.server.commands.SummonCommand;
|
| 123 | import net.minecraft.server.commands.SwingCommand;
|
| 124 | import net.minecraft.server.commands.TagCommand;
|
| 125 | import net.minecraft.server.commands.TeamCommand;
|
| 126 | import net.minecraft.server.commands.TeamMsgCommand;
|
| 127 | import net.minecraft.server.commands.TeleportCommand;
|
| 128 | import net.minecraft.server.commands.TellRawCommand;
|
| 129 | import net.minecraft.server.commands.TickCommand;
|
| 130 | import net.minecraft.server.commands.TimeCommand;
|
| 131 | import net.minecraft.server.commands.TitleCommand;
|
| 132 | import net.minecraft.server.commands.TransferCommand;
|
| 133 | import net.minecraft.server.commands.TriggerCommand;
|
| 134 | import net.minecraft.server.commands.UnpublishCommand;
|
| 135 | import net.minecraft.server.commands.VersionCommand;
|
| 136 | import net.minecraft.server.commands.WardenSpawnTrackerCommand;
|
| 137 | import net.minecraft.server.commands.WaypointCommand;
|
| 138 | import net.minecraft.server.commands.WeatherCommand;
|
| 139 | import net.minecraft.server.commands.WhitelistCommand;
|
| 140 | import net.minecraft.server.commands.WorldBorderCommand;
|
| 141 | import net.minecraft.server.commands.data.DataCommands;
|
| 142 | import net.minecraft.server.commands.item.ItemCommands;
|
| 143 | import net.minecraft.server.level.ServerPlayer;
|
| 144 | import net.minecraft.server.permissions.PermissionCheck;
|
| 145 | import net.minecraft.server.permissions.PermissionProviderCheck;
|
| 146 | import net.minecraft.server.permissions.PermissionSet;
|
| 147 | import net.minecraft.server.permissions.PermissionSetSupplier;
|
| 148 | import net.minecraft.server.permissions.Permissions;
|
| 149 | import net.minecraft.tags.TagKey;
|
| 150 | import net.minecraft.util.Util;
|
| 151 | import net.minecraft.util.profiling.Profiler;
|
| 152 | import net.minecraft.util.profiling.jfr.JvmProfiler;
|
| 153 | import net.minecraft.world.flag.FeatureFlagSet;
|
| 154 | import net.minecraft.world.flag.FeatureFlags;
|
| 155 | import net.minecraft.world.level.gamerules.GameRules;
|
| 156 | import net.minecraft.world.phys.Vec2;
|
| 157 | import net.minecraft.world.phys.Vec3;
|
| 158 | import org.jspecify.annotations.Nullable;
|
| 159 | import org.slf4j.Logger;
|
| 160 |
|
| 161 | public class Commands {
|
| 162 | public static final String COMMAND_PREFIX = "/";
|
| 163 | private static final ThreadLocal<@Nullable ExecutionContext<CommandSourceStack>> CURRENT_EXECUTION_CONTEXT = new ThreadLocal<>();
|
| 164 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 165 | public static final PermissionCheck LEVEL_ALL = PermissionCheck.AlwaysPass.INSTANCE;
|
| 166 | public static final PermissionCheck LEVEL_MODERATORS = new PermissionCheck.Require(Permissions.COMMANDS_MODERATOR);
|
| 167 | public static final PermissionCheck LEVEL_GAMEMASTERS = new PermissionCheck.Require(Permissions.COMMANDS_GAMEMASTER);
|
| 168 | public static final PermissionCheck LEVEL_ADMINS = new PermissionCheck.Require(Permissions.COMMANDS_ADMIN);
|
| 169 | public static final PermissionCheck LEVEL_OWNERS = new PermissionCheck.Require(Permissions.COMMANDS_OWNER);
|
| 170 | private static final ClientboundCommandsPacket.NodeInspector<CommandSourceStack> COMMAND_NODE_INSPECTOR = new ClientboundCommandsPacket.NodeInspector<CommandSourceStack>() {
|
| 171 | private final CommandSourceStack noPermissionSource = Commands.createCompilationContext(PermissionSet.NO_PERMISSIONS);
|
| 172 |
|
| 173 | @Override
|
| 174 | public @Nullable Identifier suggestionId(final ArgumentCommandNode<CommandSourceStack, ?> node) {
|
| 175 | SuggestionProvider<CommandSourceStack> suggestionProvider = node.getCustomSuggestions();
|
| 176 | return suggestionProvider != null ? SuggestionProviders.getName(suggestionProvider) : null;
|
| 177 | }
|
| 178 |
|
| 179 | @Override
|
| 180 | public boolean isExecutable(final CommandNode<CommandSourceStack> node) {
|
| 181 | return node.getCommand() != null;
|
| 182 | }
|
| 183 |
|
| 184 | @Override
|
| 185 | public boolean isRestricted(final CommandNode<CommandSourceStack> node) {
|
| 186 | Predicate<CommandSourceStack> requirement = node.getRequirement();
|
| 187 | return !requirement.test(this.noPermissionSource);
|
| 188 | }
|
| 189 | };
|
| 190 | private final CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher<>();
|
| 191 |
|
| 192 | public Commands(final Commands.CommandSelection commandSelection, final CommandBuildContext context) {
|
| 193 | AdvancementCommands.register(this.dispatcher);
|
| 194 | AttributeCommand.register(this.dispatcher, context);
|
| 195 | ExecuteCommand.register(this.dispatcher, context);
|
| 196 | BossBarCommands.register(this.dispatcher, context);
|
| 197 | ClearInventoryCommands.register(this.dispatcher, context);
|
| 198 | CloneCommands.register(this.dispatcher, context);
|
| 199 | ComputeCommand.register(this.dispatcher, context);
|
| 200 | DamageCommand.register(this.dispatcher, context);
|
| 201 | DataCommands.register(this.dispatcher, context);
|
| 202 | DataPackCommand.register(this.dispatcher, context);
|
| 203 | DebugCommand.register(this.dispatcher);
|
| 204 | DefaultGameModeCommands.register(this.dispatcher);
|
| 205 | DialogCommand.register(this.dispatcher, context);
|
| 206 | DifficultyCommand.register(this.dispatcher);
|
| 207 | EffectCommands.register(this.dispatcher, context);
|
| 208 | EmoteCommands.register(this.dispatcher);
|
| 209 | EnchantCommand.register(this.dispatcher, context);
|
| 210 | ExperienceCommand.register(this.dispatcher);
|
| 211 | FillCommand.register(this.dispatcher, context);
|
| 212 | FillBiomeCommand.register(this.dispatcher, context);
|
| 213 | ForceLoadCommand.register(this.dispatcher);
|
| 214 | FunctionCommand.register(this.dispatcher);
|
| 215 | GameModeCommand.register(this.dispatcher);
|
| 216 | GameRuleCommand.register(this.dispatcher, context);
|
| 217 | GiveCommand.register(this.dispatcher, context);
|
| 218 | HelpCommand.register(this.dispatcher);
|
| 219 | ItemCommands.register(this.dispatcher, context);
|
| 220 | KickCommand.register(this.dispatcher);
|
| 221 | KillCommand.register(this.dispatcher);
|
| 222 | ListPlayersCommand.register(this.dispatcher);
|
| 223 | LocateCommand.register(this.dispatcher, context);
|
| 224 | LootCommand.register(this.dispatcher, context);
|
| 225 | MsgCommand.register(this.dispatcher);
|
| 226 | SwingCommand.register(this.dispatcher);
|
| 227 | ParticleCommand.register(this.dispatcher, context);
|
| 228 | PlaceCommand.register(this.dispatcher, context);
|
| 229 | PlaySoundCommand.register(this.dispatcher);
|
| 230 | PostEffectCommand.register(this.dispatcher);
|
| 231 | RandomCommand.register(this.dispatcher);
|
| 232 | ReloadCommand.register(this.dispatcher);
|
| 233 | RecipeCommand.register(this.dispatcher);
|
| 234 | FetchProfileCommand.register(this.dispatcher);
|
| 235 | ReturnCommand.register(this.dispatcher);
|
| 236 | RideCommand.register(this.dispatcher);
|
| 237 | RotateCommand.register(this.dispatcher);
|
| 238 | SayCommand.register(this.dispatcher);
|
| 239 | ScheduleCommand.register(this.dispatcher);
|
| 240 | ScoreboardCommand.register(this.dispatcher, context);
|
| 241 | SeedCommand.register(this.dispatcher, commandSelection != Commands.CommandSelection.INTEGRATED);
|
| 242 | VersionCommand.register(this.dispatcher, commandSelection != Commands.CommandSelection.INTEGRATED);
|
| 243 | SetBlockCommand.register(this.dispatcher, context);
|
| 244 | SetSpawnCommand.register(this.dispatcher);
|
| 245 | SetWorldSpawnCommand.register(this.dispatcher);
|
| 246 | SpectateCommand.register(this.dispatcher);
|
| 247 | SpreadPlayersCommand.register(this.dispatcher);
|
| 248 | StopSoundCommand.register(this.dispatcher);
|
| 249 | StopwatchCommand.register(this.dispatcher);
|
| 250 | SummonCommand.register(this.dispatcher, context);
|
| 251 | TagCommand.register(this.dispatcher);
|
| 252 | TeamCommand.register(this.dispatcher, context);
|
| 253 | TeamMsgCommand.register(this.dispatcher);
|
| 254 | TeleportCommand.register(this.dispatcher);
|
| 255 | TellRawCommand.register(this.dispatcher, context);
|
| 256 | TestCommand.register(this.dispatcher, context);
|
| 257 | TickCommand.register(this.dispatcher);
|
| 258 | TimeCommand.register(this.dispatcher, context);
|
| 259 | TitleCommand.register(this.dispatcher, context);
|
| 260 | TriggerCommand.register(this.dispatcher);
|
| 261 | WaypointCommand.register(this.dispatcher, context);
|
| 262 | WeatherCommand.register(this.dispatcher);
|
| 263 | WorldBorderCommand.register(this.dispatcher);
|
| 264 | if (JvmProfiler.INSTANCE.isAvailable()) {
|
| 265 | JfrCommand.register(this.dispatcher);
|
| 266 | }
|
| 267 |
|
| 268 | if (SharedConstants.DEBUG_CHASE_COMMAND) {
|
| 269 | ChaseCommand.register(this.dispatcher);
|
| 270 | }
|
| 271 |
|
| 272 | if (SharedConstants.DEBUG_DEV_COMMANDS || SharedConstants.IS_RUNNING_IN_IDE) {
|
| 273 | RaidCommand.register(this.dispatcher, context);
|
| 274 | DebugPathCommand.register(this.dispatcher);
|
| 275 | DebugMobSpawningCommand.register(this.dispatcher);
|
| 276 | WardenSpawnTrackerCommand.register(this.dispatcher);
|
| 277 | SpawnArmorTrimsCommand.register(this.dispatcher);
|
| 278 | ServerPackCommand.register(this.dispatcher);
|
| 279 | if (commandSelection.includeDedicated) {
|
| 280 | DebugConfigCommand.register(this.dispatcher, context);
|
| 281 | }
|
| 282 | }
|
| 283 |
|
| 284 | if (commandSelection.includeDedicated) {
|
| 285 | BanIpCommands.register(this.dispatcher);
|
| 286 | BanListCommands.register(this.dispatcher);
|
| 287 | BanPlayerCommands.register(this.dispatcher);
|
| 288 | DeOpCommands.register(this.dispatcher);
|
| 289 | OpCommand.register(this.dispatcher);
|
| 290 | PardonCommand.register(this.dispatcher);
|
| 291 | PardonIpCommand.register(this.dispatcher);
|
| 292 | PerfCommand.register(this.dispatcher);
|
| 293 | SaveAllCommand.register(this.dispatcher);
|
| 294 | SaveOffCommand.register(this.dispatcher);
|
| 295 | SaveOnCommand.register(this.dispatcher);
|
| 296 | SetPlayerIdleTimeoutCommand.register(this.dispatcher);
|
| 297 | StopCommand.register(this.dispatcher);
|
| 298 | TransferCommand.register(this.dispatcher);
|
| 299 | WhitelistCommand.register(this.dispatcher);
|
| 300 | }
|
| 301 |
|
| 302 | if (commandSelection.includeIntegrated) {
|
| 303 | PublishCommand.register(this.dispatcher);
|
| 304 | UnpublishCommand.register(this.dispatcher);
|
| 305 | }
|
| 306 |
|
| 307 | this.dispatcher.setConsumer(ExecutionCommandSource.resultConsumer());
|
| 308 | }
|
| 309 |
|
| 310 | public static <S> ParseResults<S> mapSource(final ParseResults<S> parse, final UnaryOperator<S> sourceOperator) {
|
| 311 | CommandContextBuilder<S> context = parse.getContext();
|
| 312 | CommandContextBuilder<S> source = context.withSource(sourceOperator.apply(context.getSource()));
|
| 313 | return new ParseResults<>(source, parse.getReader(), parse.getExceptions());
|
| 314 | }
|
| 315 |
|
| 316 | public void performPrefixedCommand(final CommandSourceStack sender, String command) {
|
| 317 | command = trimOptionalPrefix(command);
|
| 318 | this.performCommand(this.dispatcher.parse(command, sender), command);
|
| 319 | }
|
| 320 |
|
| 321 | public static String trimOptionalPrefix(final String command) {
|
| 322 | return command.startsWith("/") ? command.substring(1) : command;
|
| 323 | }
|
| 324 |
|
| 325 | public void performCommand(final ParseResults<CommandSourceStack> command, final String commandString) {
|
| 326 | CommandSourceStack sender = command.getContext().getSource();
|
| 327 | Profiler.get().push(() -> "/" + commandString);
|
| 328 | ContextChain<CommandSourceStack> commandChain = finishParsing(command, commandString, sender);
|
| 329 |
|
| 330 | try {
|
| 331 | if (commandChain != null) {
|
| 332 | executeCommandInContext(
|
| 333 | sender,
|
| 334 | executionContext -> ExecutionContext.queueInitialCommandExecution(executionContext, commandString, commandChain, sender, CommandResultCallback.EMPTY)
|
| 335 | );
|
| 336 | }
|
| 337 | } catch (Exception e) {
|
| 338 | MutableComponent hover = Component.literal(e.getMessage() == null ? e.getClass().getName() : e.getMessage());
|
| 339 | if (LOGGER.isDebugEnabled()) {
|
| 340 | LOGGER.error("Command exception: /{}", commandString, e);
|
| 341 | StackTraceElement[] stackTrace = e.getStackTrace();
|
| 342 |
|
| 343 | for (int i = 0; i < Math.min(stackTrace.length, 3); i++) {
|
| 344 | hover.append("\n\n")
|
| 345 | .append(stackTrace[i].getMethodName())
|
| 346 | .append("\n ")
|
| 347 | .append(stackTrace[i].getFileName())
|
| 348 | .append(":")
|
| 349 | .append(String.valueOf(stackTrace[i].getLineNumber()));
|
| 350 | }
|
| 351 | }
|
| 352 |
|
| 353 | sender.sendFailure(Component.translatable("command.failed").withStyle(s -> s.withHoverEvent(new HoverEvent.ShowText(hover))));
|
| 354 | if (SharedConstants.DEBUG_VERBOSE_COMMAND_ERRORS || SharedConstants.IS_RUNNING_IN_IDE) {
|
| 355 | sender.sendFailure(Component.literal(Util.describeError(e)));
|
| 356 | LOGGER.error("'/{}' threw an exception", commandString, e);
|
| 357 | }
|
| 358 | } finally {
|
| 359 | Profiler.get().pop();
|
| 360 | }
|
| 361 | }
|
| 362 |
|
| 363 | private static @Nullable ContextChain<CommandSourceStack> finishParsing(
|
| 364 | final ParseResults<CommandSourceStack> command, final String commandString, final CommandSourceStack sender
|
| 365 | ) {
|
| 366 | try {
|
| 367 | validateParseResults(command);
|
| 368 | return ContextChain.tryFlatten(command.getContext().build(commandString))
|
| 369 | .orElseThrow(() -> CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(command.getReader()));
|
| 370 | } catch (CommandSyntaxException e) {
|
| 371 | sender.sendFailure(ComponentUtils.fromMessage(e.getRawMessage()));
|
| 372 | if (e.getInput() != null && e.getCursor() >= 0) {
|
| 373 | int cursor = Math.min(e.getInput().length(), e.getCursor());
|
| 374 | MutableComponent context = Component.empty()
|
| 375 | .withStyle(ChatFormatting.GRAY)
|
| 376 | .withStyle(s -> s.withClickEvent(new ClickEvent.SuggestCommand("/" + commandString)));
|
| 377 | if (cursor > 10) {
|
| 378 | context.append(CommonComponents.ELLIPSIS);
|
| 379 | }
|
| 380 |
|
| 381 | context.append(e.getInput().substring(Math.max(0, cursor - 10), cursor));
|
| 382 | if (cursor < e.getInput().length()) {
|
| 383 | Component remaining = Component.literal(e.getInput().substring(cursor)).withStyle(ChatFormatting.RED, ChatFormatting.UNDERLINE);
|
| 384 | context.append(remaining);
|
| 385 | }
|
| 386 |
|
| 387 | context.append(Component.translatable("command.context.here").withStyle(ChatFormatting.RED, ChatFormatting.ITALIC));
|
| 388 | sender.sendFailure(context);
|
| 389 | }
|
| 390 |
|
| 391 | return null;
|
| 392 | }
|
| 393 | }
|
| 394 |
|
| 395 | public static void executeCommandInContext(final CommandSourceStack context, final Consumer<ExecutionContext<CommandSourceStack>> config) {
|
| 396 | ExecutionContext<CommandSourceStack> currentContext = CURRENT_EXECUTION_CONTEXT.get();
|
| 397 | boolean isTopContext = currentContext == null;
|
| 398 | if (isTopContext) {
|
| 399 | GameRules gameRules = context.getLevel().getGameRules();
|
| 400 | int chainLimit = Math.max(1, gameRules.get(GameRules.MAX_COMMAND_SEQUENCE_LENGTH));
|
| 401 | int forkLimit = gameRules.get(GameRules.MAX_COMMAND_FORKS);
|
| 402 |
|
| 403 | try (ExecutionContext<CommandSourceStack> executionContext = new ExecutionContext<>(chainLimit, forkLimit, Profiler.get())) {
|
| 404 | CURRENT_EXECUTION_CONTEXT.set(executionContext);
|
| 405 | config.accept(executionContext);
|
| 406 | executionContext.runCommandQueue();
|
| 407 | } finally {
|
| 408 | CURRENT_EXECUTION_CONTEXT.set(null);
|
| 409 | }
|
| 410 | } else {
|
| 411 | config.accept(currentContext);
|
| 412 | }
|
| 413 | }
|
| 414 |
|
| 415 | public void sendCommands(final ServerPlayer player) {
|
| 416 | Map<CommandNode<CommandSourceStack>, CommandNode<CommandSourceStack>> playerCommands = new HashMap<>();
|
| 417 | RootCommandNode<CommandSourceStack> root = new RootCommandNode<>();
|
| 418 | playerCommands.put(this.dispatcher.getRoot(), root);
|
| 419 | fillUsableCommands(this.dispatcher.getRoot(), root, player.createCommandSourceStack(), playerCommands);
|
| 420 | player.connection.send(new ClientboundCommandsPacket(root, COMMAND_NODE_INSPECTOR));
|
| 421 | }
|
| 422 |
|
| 423 | private static <S> void fillUsableCommands(
|
| 424 | final CommandNode<S> source, final CommandNode<S> target, final S commandFilter, final Map<CommandNode<S>, CommandNode<S>> converted
|
| 425 | ) {
|
| 426 | for (CommandNode<S> child : source.getChildren()) {
|
| 427 | if (child.canUse(commandFilter)) {
|
| 428 | ArgumentBuilder<S, ?> builder = child.createBuilder();
|
| 429 | if (builder.getRedirect() != null) {
|
| 430 | builder.redirect(converted.get(builder.getRedirect()));
|
| 431 | }
|
| 432 |
|
| 433 | CommandNode<S> node = builder.build();
|
| 434 | converted.put(child, node);
|
| 435 | target.addChild(node);
|
| 436 | if (!child.getChildren().isEmpty()) {
|
| 437 | fillUsableCommands(child, node, commandFilter, converted);
|
| 438 | }
|
| 439 | }
|
| 440 | }
|
| 441 | }
|
| 442 |
|
| 443 | public static LiteralArgumentBuilder<CommandSourceStack> literal(final String literal) {
|
| 444 | return LiteralArgumentBuilder.literal(literal);
|
| 445 | }
|
| 446 |
|
| 447 | public static <T> RequiredArgumentBuilder<CommandSourceStack, T> argument(final String name, final ArgumentType<T> type) {
|
| 448 | return RequiredArgumentBuilder.argument(name, type);
|
| 449 | }
|
| 450 |
|
| 451 | public static Predicate<String> createValidator(final Commands.ParseFunction parser) {
|
| 452 | return value -> {
|
| 453 | try {
|
| 454 | parser.parse(new StringReader(value));
|
| 455 | return true;
|
| 456 | } catch (CommandSyntaxException ignored) {
|
| 457 | return false;
|
| 458 | }
|
| 459 | };
|
| 460 | }
|
| 461 |
|
| 462 | public CommandDispatcher<CommandSourceStack> getDispatcher() {
|
| 463 | return this.dispatcher;
|
| 464 | }
|
| 465 |
|
| 466 | public static <S> void validateParseResults(final ParseResults<S> command) throws CommandSyntaxException {
|
| 467 | CommandSyntaxException parseException = getParseException(command);
|
| 468 | if (parseException != null) {
|
| 469 | throw parseException;
|
| 470 | }
|
| 471 | }
|
| 472 |
|
| 473 | public static <S> @Nullable CommandSyntaxException getParseException(final ParseResults<S> parse) {
|
| 474 | if (!parse.getReader().canRead()) {
|
| 475 | return null;
|
| 476 | } else if (parse.getExceptions().size() == 1) {
|
| 477 | return parse.getExceptions().values().iterator().next();
|
| 478 | } else {
|
| 479 | return parse.getContext().getRange().isEmpty()
|
| 480 | ? CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(parse.getReader())
|
| 481 | : CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownArgument().createWithContext(parse.getReader());
|
| 482 | }
|
| 483 | }
|
| 484 |
|
| 485 | public static CommandBuildContext createValidationContext(final HolderLookup.Provider registries) {
|
| 486 | return new CommandBuildContext() {
|
| 487 | @Override
|
| 488 | public FeatureFlagSet enabledFeatures() {
|
| 489 | return FeatureFlags.REGISTRY.allFlags();
|
| 490 | }
|
| 491 |
|
| 492 | @Override
|
| 493 | public Stream<ResourceKey<? extends Registry<?>>> listRegistryKeys() {
|
| 494 | return registries.listRegistryKeys();
|
| 495 | }
|
| 496 |
|
| 497 | @Override
|
| 498 | public <T> Optional<HolderLookup.RegistryLookup<T>> lookup(final ResourceKey<? extends Registry<? extends T>> key) {
|
| 499 | return registries.lookup(key).map(this::createLookup);
|
| 500 | }
|
| 501 |
|
| 502 | private <T> HolderLookup.RegistryLookup.Delegate<T> createLookup(final HolderLookup.RegistryLookup<T> original) {
|
| 503 | return new HolderLookup.RegistryLookup.Delegate<T>() {
|
| 504 | @Override
|
| 505 | public HolderLookup.RegistryLookup<T> parent() {
|
| 506 | return original;
|
| 507 | }
|
| 508 |
|
| 509 | @Override
|
| 510 | public Optional<HolderSet.Named<T>> get(final TagKey<T> id) {
|
| 511 | return Optional.of(this.getOrThrow(id));
|
| 512 | }
|
| 513 |
|
| 514 | @Override
|
| 515 | public HolderSet.Named<T> getOrThrow(final TagKey<T> id) {
|
| 516 | Optional<HolderSet.Named<T>> tag = this.parent().get(id);
|
| 517 | return tag.orElseGet(() -> HolderSet.emptyNamed(this.parent(), id));
|
| 518 | }
|
| 519 | };
|
| 520 | }
|
| 521 | };
|
| 522 | }
|
| 523 |
|
| 524 | public static void validate() {
|
| 525 | CommandBuildContext context = createValidationContext(VanillaRegistries.createWorldLookup());
|
| 526 | CommandDispatcher<CommandSourceStack> dispatcher = new Commands(Commands.CommandSelection.ALL, context).getDispatcher();
|
| 527 | RootCommandNode<CommandSourceStack> root = dispatcher.getRoot();
|
| 528 | dispatcher.findAmbiguities(
|
| 529 | (parent, child, sibling, ambiguities) -> LOGGER.warn(
|
| 530 | "Ambiguity between arguments {} and {} with inputs: {}", dispatcher.getPath(child), dispatcher.getPath(sibling), ambiguities
|
| 531 | )
|
| 532 | );
|
| 533 | Set<ArgumentType<?>> usedArgumentTypes = ArgumentUtils.findUsedArgumentTypes(root);
|
| 534 | Set<ArgumentType<?>> unregisteredTypes = usedArgumentTypes.stream()
|
| 535 | .filter(arg -> !ArgumentTypeInfos.isClassRecognized(arg.getClass()))
|
| 536 | .collect(Collectors.toSet());
|
| 537 | if (!unregisteredTypes.isEmpty()) {
|
| 538 | LOGGER.warn("Missing type registration for following arguments:\n {}", unregisteredTypes.stream().map(arg -> "\t" + arg).collect(Collectors.joining(",\n")));
|
| 539 | throw new IllegalStateException("Unregistered argument types");
|
| 540 | }
|
| 541 | }
|
| 542 |
|
| 543 | public static <T extends PermissionSetSupplier> PermissionProviderCheck<T> hasPermission(final PermissionCheck permission) {
|
| 544 | return new PermissionProviderCheck<>(permission);
|
| 545 | }
|
| 546 |
|
| 547 | public static CommandSourceStack createCompilationContext(final PermissionSet compilationPermissions) {
|
| 548 | return new CommandSourceStack(CommandSource.NULL, Vec3.ZERO, Vec2.ZERO, null, compilationPermissions, CommonComponents.EMPTY, null);
|
| 549 | }
|
| 550 |
|
| 551 | /**
|
| 552 | * Access widened by fabric-command-api-v2 to accessible
|
| 553 | */
|
| 554 | public enum CommandSelection {
|
| 555 | ALL(true, true),
|
| 556 | DEDICATED(false, true),
|
| 557 | INTEGRATED(true, false);
|
| 558 |
|
| 559 | /**
|
| 560 | * Access widened by fabric-command-api-v2 to accessible
|
| 561 | */
|
| 562 | public final boolean includeIntegrated;
|
| 563 | /**
|
| 564 | * Access widened by fabric-command-api-v2 to accessible
|
| 565 | */
|
| 566 | public final boolean includeDedicated;
|
| 567 |
|
| 568 | CommandSelection(final boolean includeIntegrated, final boolean includeDedicated) {
|
| 569 | this.includeIntegrated = includeIntegrated;
|
| 570 | this.includeDedicated = includeDedicated;
|
| 571 | }
|
| 572 | }
|
| 573 |
|
| 574 | @FunctionalInterface
|
| 575 | public interface ParseFunction {
|
| 576 | void parse(StringReader value) throws CommandSyntaxException;
|
| 577 | }
|
| 578 | }
|
| 579 |
|