aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/cc/polyfrost/oneconfig/utils/commands/CommandManager.java
blob: f168b8f0df339f3bf5a69907e566cbed2abfe79b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package cc.polyfrost.oneconfig.utils.commands;

import cc.polyfrost.oneconfig.libs.universal.ChatColor;
import cc.polyfrost.oneconfig.libs.universal.UChat;
import cc.polyfrost.oneconfig.utils.commands.annotations.*;
import cc.polyfrost.oneconfig.utils.commands.arguments.*;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraftforge.client.ClientCommandHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Handles the registration of OneConfig commands.
 *
 * @see Command
 */
public class CommandManager {
    public static final CommandManager INSTANCE = new CommandManager();
    private final HashMap<Class<?>, ArgumentParser<?>> parsers = new HashMap<>();
    private static final String NOT_FOUND_TEXT = "Command not found! Type /@ROOT_COMMAND@ help for help.";
    private static final String METHOD_RUN_ERROR = "Error while running @ROOT_COMMAND@ method! Please report this to the developer.";

    private CommandManager() {
        addParser(new StringParser());
        addParser(new IntegerParser());
        addParser(new IntegerParser(), int.class);
        addParser(new DoubleParser());
        addParser(new DoubleParser(), double.class);
        addParser(new FloatParser());
        addParser(new FloatParser(), float.class);
        addParser(new BooleanParser());
        addParser(new BooleanParser(), boolean.class);
    }

    /**
     * Adds a parser to the parsers map.
     *
     * @param parser The parser to add.
     * @param clazz The class of the parser.
     */
    public void addParser(ArgumentParser<?> parser, Class<?> clazz) {
        parsers.put(clazz, parser);
    }

    /**
     * Adds a parser to the parsers map.
     * @param parser The parser to add.
     */
    public void addParser(ArgumentParser<?> parser) {
        addParser(parser, parser.typeClass);
    }

    /**
     * Registers the provided command.
     *
     * @param command The command to register.
     */
    public void registerCommand(Object command) {
        Class<?> clazz = command.getClass();
        if (clazz.isAnnotationPresent(Command.class)) {
            final Command annotation = clazz.getAnnotation(Command.class);
            ArrayList<InternalCommand.InternalCommandInvoker> mainCommandFuncs = new ArrayList<>();

            for (Method method : clazz.getDeclaredMethods()) {
                if (method.isAnnotationPresent(Main.class) && method.getParameterCount() == 0) {
                    mainCommandFuncs.add(new InternalCommand.InternalCommandInvoker(annotation.value(), annotation.aliases(), method));
                    break;
                }
            }

            final InternalCommand root = new InternalCommand(annotation.value(), annotation.aliases(), annotation.description().trim().isEmpty() ? "Main command for " + annotation.value() : annotation.description(), mainCommandFuncs);
            addToInvokers(clazz.getDeclaredClasses(), root);
            ClientCommandHandler.instance.registerCommand(new CommandBase() {
                @Override
                public String getCommandName() {
                    return annotation.value();
                }

                @Override
                public String getCommandUsage(ICommandSender sender) {
                    return "/" + annotation.value();
                }

                @Override
                public void processCommand(ICommandSender sender, String[] args) {
                    if (args.length == 0) {
                        if (!root.invokers.isEmpty()) {
                            try {
                                root.invokers.stream().findFirst().get().method.invoke(null);
                            } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException | ExceptionInInitializerError e) {
                                UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + METHOD_RUN_ERROR);
                            }
                        }
                    } else {
                        if (annotation.helpCommand() && args[0].equalsIgnoreCase("help")) {
                            UChat.chat(sendHelpCommand(root));
                        } else {
                            for (InternalCommand command : root.children) {
                                String result = runThroughCommands(command, 0, args);
                                if (result == null) {
                                    return;
                                } else if (!result.equals(NOT_FOUND_TEXT)) {
                                    UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + result.replace("@ROOT_COMMAND@", getCommandName()));
                                    return;
                                }
                            }
                            UChat.chat(ChatColor.RED.toString() + ChatColor.BOLD + NOT_FOUND_TEXT.replace("@ROOT_COMMAND@", getCommandName()));
                        }
                    }
                }

                @Override
                public int getRequiredPermissionLevel() {
                    return -1;
                }
            });
        }
    }

    private String sendHelpCommand(InternalCommand root) {
        StringBuilder builder = new StringBuilder();
        builder.append(ChatColor.GOLD.toString() + "Help for " + ChatColor.BOLD + root.name + ChatColor.RESET + ChatColor.GOLD + ":\n");
        builder.append("\n");
        for (InternalCommand command : root.children) {
            runThroughCommandsHelp(root.name, root, builder);
        }
        builder.append("\n" + ChatColor.GOLD + "Aliases: " + ChatColor.BOLD);
        int index = 0;
        for (String alias : root.aliases) {
            ++index;
            builder.append(alias + (index < root.aliases.length ? ", " : ""));
        }
        builder.append("\n");
        return builder.toString();
    }

    private void runThroughCommandsHelp(String append, InternalCommand command, StringBuilder builder) {
        for (InternalCommand.InternalCommandInvoker invoker : command.invokers) {
            builder.append("\n" + ChatColor.GOLD + "/" + append + " " + command.name);
            for (Parameter parameter : invoker.method.getParameters()) {
                String name = parameter.getName();
                if (parameter.isAnnotationPresent(Name.class)) {
                    name = parameter.getAnnotation(Name.class).value();
                }
                builder.append(" <" + name + ">");
            }
            if (!command.description.trim().isEmpty()) {
                builder.append(": " + ChatColor.BOLD + command.description);
            }
        }
        for (InternalCommand subCommand : command.children) {
            runThroughCommandsHelp(append + " " + command.name, subCommand, builder);
        }
    }

    private String runThroughCommands(InternalCommand command, int layer, String[] args) {
        int newLayer = layer + 1;
        if (command.isEqual(args[layer]) && !command.invokers.isEmpty()) {
            Set<InternalCommand.InternalCommandInvoker> invokers = command.invokers.stream().filter(invoker -> newLayer == args.length - invoker.parameterTypes.length).sorted(Comparator.comparingInt((a) -> a.method.getAnnotation(Main.class).priority())).collect(Collectors.toSet());
            if (!invokers.isEmpty()) {
                for (InternalCommand.InternalCommandInvoker invoker : invokers) {
                    try {
                        String a = tryInvoker(invoker, newLayer, args);
                        if (a == null) {
                            return null;
                        } else if (a.contains(METHOD_RUN_ERROR)) {
                            return a;
                        }
                    } catch (Exception ignored) {

                    }
                }
            } else {
                for (InternalCommand subCommand : command.children) {
                    String result = runThroughCommands(subCommand, newLayer, args);
                    if (result == null) {
                        return null;
                    } else if (!result.equals(NOT_FOUND_TEXT)) {
                        return result;
                    }
                }
            }
        }
        return NOT_FOUND_TEXT;
    }

    private String tryInvoker(InternalCommand.InternalCommandInvoker invoker, int newLayer, String[] args) {
        try {
            ArrayList<Object> params = new ArrayList<>();
            int processed = newLayer;
            int currentParam = 0;
            while (processed < args.length) {
                Parameter param = invoker.method.getParameters()[currentParam];
                if (param.isAnnotationPresent(Greedy.class) && currentParam + 1 != invoker.method.getParameterCount()) {
                    return "Parsing failed: Greedy parameter must be the last one.";
                }
                ArgumentParser<?> parser = parsers.get(param.getType());
                if (parser == null) {
                    return "No parser for " + invoker.method.getParameterTypes()[currentParam].getSimpleName() + "! Please report this to the mod author.";
                }
                try {
                    Arguments arguments = new Arguments(Arrays.copyOfRange(args, processed, args.length), param.isAnnotationPresent(Greedy.class));
                    try {
                        Object a = parser.parse(arguments);
                        if (a != null) {
                            params.add(a);
                            processed += arguments.getPosition();
                            currentParam++;
                        } else {
                            return "Failed to parse " + param.getType().getSimpleName() + "! Please report this to the mod author.";
                        }
                    } catch (Exception e) {
                        return "A " + e.getClass().getSimpleName() + " has occured while try to parse " + param.getType().getSimpleName() + "! Please report this to the mod author.";
                    }
                } catch (Exception e) {
                    return "A " + e.getClass().getSimpleName() + " has occured while try to parse " + param.getType().getSimpleName() + "! Please report this to the mod author.";
                }
            }
            invoker.method.invoke(null, params.toArray());
            return null;
        } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException | ExceptionInInitializerError e) {
            return ChatColor.RED.toString() + ChatColor.BOLD + METHOD_RUN_ERROR;
        }
    }

    private void addToInvokers(Class<?>[] classes, InternalCommand parent) {
        for (Class<?> clazz : classes) {
            if (clazz.isAnnotationPresent(SubCommand.class)) {
                SubCommand annotation = clazz.getAnnotation(SubCommand.class);
                ArrayList<InternalCommand.InternalCommandInvoker> mainMethods = new ArrayList<>();
                for (Method method : clazz.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(Main.class)) {
                        mainMethods.add(new InternalCommand.InternalCommandInvoker(annotation.value(), annotation.aliases(), method));
                    }
                }
                InternalCommand command = new InternalCommand(annotation.value(), annotation.aliases(), annotation.description(), mainMethods);
                parent.children.add(command);
                addToInvokers(clazz.getDeclaredClasses(), command);
            }
        }
    }

    private static class InternalCommand {
        public final String name;
        public final String[] aliases;
        public final String description;
        public final ArrayList<InternalCommandInvoker> invokers;
        public final ArrayList<InternalCommand> children = new ArrayList<>();

        public InternalCommand(String name, String[] aliases, String description, ArrayList<InternalCommandInvoker> invokers) {
            this.name = name;
            this.aliases = aliases;
            this.invokers = invokers;
            this.description = description;
        }

        public boolean isEqual(String name) {
            if (this.name.equals(name)) {
                return true;
            } else {
                for (String alias : aliases) {
                    if (alias.equals(name)) {
                        return true;
                    }
                }
            }
            return false;
        }

        public static class InternalCommandInvoker {
            public final String name;
            public final String[] aliases;
            public final Method method;
            public final Parameter[] parameterTypes;

            public InternalCommandInvoker(String name, String[] aliases, Method method) {
                if (!Modifier.isStatic(method.getModifiers())) {
                    throw new IllegalArgumentException("All command methods must be static!");
                }
                this.name = name;
                this.aliases = aliases;
                this.method = method;
                this.parameterTypes = method.getParameters().clone();
                if (Modifier.isPrivate(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) {
                    method.setAccessible(true);
                }
            }
        }
    }
}