From 86d0c737cc2528486d14178fa82655d66f90660b Mon Sep 17 00:00:00 2001
From: Jason Penilla <11360596+jpenilla@users.noreply.github.com>
Date: Tue, 30 Jul 2024 11:42:55 -0700
Subject: [PATCH] Preserve command node when re-registering modern commands
 through old API (#11184)

* Preserve command node when re-registering modern commands through old API

* make fix more targeted

mainly because it didn't work for vanilla commands :)
---
 patches/server/Brigadier-based-command-API.patch | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/patches/server/Brigadier-based-command-API.patch b/patches/server/Brigadier-based-command-API.patch
index b843ede5cf..e3272914f6 100644
--- a/patches/server/Brigadier-based-command-API.patch
+++ b/patches/server/Brigadier-based-command-API.patch
@@ -1517,10 +1517,10 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000
 +import com.google.common.collect.Iterators;
 +import com.mojang.brigadier.CommandDispatcher;
 +import com.mojang.brigadier.tree.CommandNode;
-+import com.mojang.brigadier.tree.LiteralCommandNode;
 +import io.papermc.paper.command.brigadier.CommandSourceStack;
 +import io.papermc.paper.command.brigadier.PaperBrigadier;
 +import io.papermc.paper.command.brigadier.PaperCommands;
++import io.papermc.paper.command.brigadier.PluginVanillaCommandWrapper;
 +import java.util.AbstractCollection;
 +import java.util.AbstractSet;
 +import java.util.ArrayList;
@@ -1604,12 +1604,18 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000
 +        return PaperBrigadier.wrapNode(node);
 +    }
 +
++    @SuppressWarnings({"unchecked", "rawtypes"})
 +    @Nullable
 +    @Override
 +    public Command put(String key, Command value) {
 +        Command old = this.get(key);
 +        this.getDispatcher().getRoot().removeCommand(key); // Override previous command
-+        this.getDispatcher().getRoot().addChild(BukkitCommandNode.of(key, value));
++        if (value instanceof PluginVanillaCommandWrapper wrapper && wrapper.getName().equals(key)) {
++            // Don't break when some plugin tries to remove and add back a plugin command registered with modern API...
++            this.getDispatcher().getRoot().addChild((CommandNode) wrapper.vanillaCommand);
++        } else {
++            this.getDispatcher().getRoot().addChild(BukkitCommandNode.of(key, value));
++        }
 +        return old;
 +    }
 +