/
CommandManager.java
851 lines (753 loc) · 35.4 KB
/
CommandManager.java
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
package net.citizensnpcs.api.command;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import com.google.common.base.Joiner;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.citizensnpcs.api.command.Arg.CompletionsProvider;
import net.citizensnpcs.api.command.Arg.FlagValidator;
import net.citizensnpcs.api.command.exception.CommandException;
import net.citizensnpcs.api.command.exception.CommandUsageException;
import net.citizensnpcs.api.command.exception.NoPermissionsException;
import net.citizensnpcs.api.command.exception.ServerCommandException;
import net.citizensnpcs.api.command.exception.UnhandledCommandException;
import net.citizensnpcs.api.command.exception.WrappedCommandException;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.util.Messaging;
import net.citizensnpcs.api.util.Paginator;
import net.citizensnpcs.api.util.SpigotUtil;
public class CommandManager implements TabCompleter {
private final Map<Class<? extends Annotation>, CommandAnnotationProcessor> annotationProcessors = Maps.newHashMap();
/*
* Mapping of commands (including aliases) with a description. Root commands
* are stored under a key of null, whereas child commands are cached under
* their respective Method. The child map has the key of the command name
* (one for each alias) with the method.
*/
private final Map<String, CommandInfo> commands = Maps.newHashMap();
private Injector injector;
public CommandManager() {
registerAnnotationProcessor(new RequirementsProcessor());
}
/**
*
* Attempt to execute a command using the root {@link Command} given. A list of method arguments may be used when
* calling the command handler method.
*
* A command handler method should follow the form <code>command(CommandContext args, CommandSender sender)</code>
* where {@link CommandSender} can be replaced with {@link Player} to only accept players. The method parameters
* must include the method args given, if any.
*
* @param command
* The command to execute
* @param args
* The arguments of the command
* @param sender
* The sender of the command
* @param methodArgs
* The method arguments to be used when calling the command handler
* @throws CommandException
* Any exceptions caused from execution of the command
*/
public void execute(org.bukkit.command.Command command, String[] args, CommandSender sender, Object... methodArgs)
throws CommandException {
// must put command into split.
String[] newArgs = new String[args.length + 1];
System.arraycopy(args, 0, newArgs, 1, args.length);
newArgs[0] = command.getName().toLowerCase();
Object[] newMethodArgs = new Object[methodArgs.length + 1];
System.arraycopy(methodArgs, 0, newMethodArgs, 1, methodArgs.length);
executeCommand(newArgs, sender, newMethodArgs);
}
private void executeCommand(String[] args, CommandSender sender, Object[] methodArgs) throws CommandException {
String cmdName = args[0].toLowerCase();
String modifier = args.length > 1 ? args[1] : "";
boolean help = modifier.toLowerCase().equals("help");
CommandInfo info = getCommand(cmdName, modifier);
if ((info == null || info.method == null)) {
if (help) {
executeHelp(args, sender);
return;
}
info = commands.get(cmdName + " *");
}
if (info == null && args.length > 2) {
info = getCommand(cmdName, args[1], args[2]);
}
if (info == null)
throw new UnhandledCommandException();
if (!info.serverCommand && sender instanceof ConsoleCommandSender)
throw new ServerCommandException();
if (!hasPermission(info, sender))
throw new NoPermissionsException();
Command cmd = info.commandAnnotation;
CommandContext context = new CommandContext(sender, args);
if (cmd.requiresFlags() && !context.hasAnyFlags())
throw new CommandUsageException("", getUsage(args, cmd));
if (context.argsLength() < cmd.min())
throw new CommandUsageException(CommandMessages.TOO_FEW_ARGUMENTS, getUsage(args, cmd));
if (cmd.max() != -1 && context.argsLength() > cmd.max())
throw new CommandUsageException(CommandMessages.TOO_MANY_ARGUMENTS, getUsage(args, cmd));
if (!cmd.flags().contains("*")) {
for (char flag : context.getFlags()) {
if (cmd.flags().indexOf(String.valueOf(flag)) == -1)
throw new CommandUsageException("Unknown flag: " + flag, getUsage(args, cmd));
}
}
methodArgs[0] = context;
for (Annotation annotation : info.annotations) {
CommandAnnotationProcessor processor = annotationProcessors.get(annotation.annotationType());
processor.process(sender, context, annotation, methodArgs);
}
if (info.methodArguments.size() > 0) {
methodArgs = Arrays.copyOf(methodArgs, methodArgs.length + info.methodArguments.size());
for (Entry<Integer, InjectedCommandArgument> entry : info.methodArguments.entrySet()) {
Class<?> desiredType = entry.getValue().paramType;
Object val = entry.getValue().getInput(context);
if (val == null) {
} else if (entry.getValue().validator != null) {
val = entry.getValue().validator.validate(context, sender,
methodArgs.length > 2 && methodArgs[2] instanceof NPC ? (NPC) methodArgs[2] : null,
val.toString());
} else if (desiredType == Material.class) {
val = SpigotUtil.isUsing1_13API() ? Material.matchMaterial(val.toString(), false)
: Material.matchMaterial(val.toString());
} else if (Enum.class.isAssignableFrom(desiredType)) {
val = matchEnum((Enum[]) desiredType.getEnumConstants(), val.toString().toUpperCase());
} else if (desiredType == double.class || desiredType == Double.class) {
val = Double.parseDouble(val.toString());
} else if (desiredType == int.class || desiredType == Integer.class) {
val = Integer.parseInt(val.toString());
} else if (desiredType == boolean.class || desiredType == Boolean.class) {
val = Boolean.parseBoolean(val.toString());
} else if (desiredType == float.class || desiredType == Float.class) {
val = Float.parseFloat(val.toString());
} else if (desiredType == Location.class) {
val = CommandContext.parseLocation(context.getSenderLocation(), val.toString());
} else if (desiredType == UUID.class) {
val = UUID.fromString(val.toString());
} else if (desiredType == Duration.class) {
val = SpigotUtil.parseDuration(val.toString());
}
methodArgs[entry.getKey()] = val;
}
}
try {
info.method.invoke(info.instance, methodArgs);
} catch (IllegalArgumentException e) {
logger.log(Level.SEVERE, "Failed to execute command", e);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE, "Failed to execute command", e);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof CommandException) {
if (e.getCause() instanceof CommandUsageException
&& ((CommandUsageException) e.getCause()).getUsage() == null) {
((CommandUsageException) e.getCause()).setUsage(getUsage(args, cmd));
}
throw (CommandException) e.getCause();
}
throw new WrappedCommandException(e.getCause());
}
}
private void executeHelp(String[] args, CommandSender sender) throws CommandException {
if (!sender.hasPermission("citizens." + args[0] + ".help"))
throw new NoPermissionsException();
int page = 1;
try {
page = args.length == 3 ? Integer.parseInt(args[2]) : page;
} catch (NumberFormatException e) {
sendSpecificHelp(sender, args[0], args[2]);
return;
}
sendHelp(sender, args[0], page);
}
/**
* A safe version of {@link #execute(org.bukkit.command.Command, String[], CommandSender, Object...)} which catches
* and logs all {@link Exception}s that occur.
*
* @see #execute(org.bukkit.command.Command, String[], CommandSender, Object...)
* @return Whether command usage should be printed
*/
public boolean executeSafe(org.bukkit.command.Command command, String[] args, CommandSender sender,
Object... methodArgs) {
try {
try {
execute(command, args, sender, methodArgs);
} catch (ServerCommandException ex) {
Messaging.sendTr(sender, CommandMessages.MUST_BE_INGAME);
} catch (CommandUsageException ex) {
if (ex.getMessage() != null && !ex.getMessage().isEmpty()) {
Messaging.sendError(sender, ex.getMessage());
}
Messaging.sendError(sender, ex.getUsage());
} catch (UnhandledCommandException ex) {
Messaging.sendErrorTr(sender, CommandMessages.UNKNOWN_COMMAND);
return false;
} catch (WrappedCommandException ex) {
if (ex.getCause() instanceof NumberFormatException) {
if (Messaging.isDebugging()) {
ex.printStackTrace();
}
Messaging.sendErrorTr(sender, CommandMessages.INVALID_NUMBER);
} else {
throw ex.getCause();
}
} catch (CommandException ex) {
Messaging.sendError(sender, ex.getMessage());
}
} catch (Throwable ex) {
ex.printStackTrace();
if (sender instanceof Player) {
Messaging.sendErrorTr(sender, CommandMessages.REPORT_ERROR);
Messaging.sendError(sender, ex.getClass().getName() + ": " + ex.getMessage());
}
}
return true;
}
/**
* Searches for the closest modifier using Levenshtein distance to the given top level command and modifier.
*
* @param command
* The top level command
* @param modifier
* The modifier to use as the base
* @return The closest modifier, or empty
*/
public String getClosestCommandModifier(String command, String modifier) {
int minDist = Integer.MAX_VALUE;
command = command.toLowerCase();
String closest = "";
for (String cmd : commands.keySet()) {
String[] split = cmd.split(" ");
if (split.length <= 1 || !split[0].equals(command))
continue;
int distance = getLevenshteinDistance(modifier, split[1]);
if (minDist > distance) {
minDist = distance;
closest = split[1];
}
}
return closest;
}
/**
* Gets the {@link CommandInfo} for the given command parts, or <code>null</code> if not found.
*
* @param commandParts
* The parts of the command
* @return The command info for the command
*/
public CommandInfo getCommand(String... commandParts) {
return commands.get(Joiner.on(' ').join(commandParts).toLowerCase());
}
/**
* Gets all modified and root commands from the given root level command. For example, if <em>/npc look</em> and
* <em>/npc jump</em> were defined, calling <code>getCommands("npc")</code> would return {@link CommandInfo}s for
* both commands.
*
* @param topLevelCommand
* The root level command
* @return The list of {@link CommandInfo}s
*/
public List<CommandInfo> getCommands(String topLevelCommand) {
topLevelCommand = topLevelCommand.toLowerCase();
List<CommandInfo> cmds = Lists.newArrayList();
for (Entry<String, CommandInfo> entry : commands.entrySet()) {
if (!entry.getKey().startsWith(topLevelCommand) || entry.getValue() == null)
continue;
cmds.add(entry.getValue());
}
return cmds;
}
private List<String> getLines(CommandSender sender, String baseCommand) {
// Ensures that commands with multiple modifiers are only added once
Set<CommandInfo> processed = Sets.newHashSet();
List<String> lines = new ArrayList<String>();
for (CommandInfo info : getCommands(baseCommand)) {
Command command = info.getCommandAnnotation();
if (processed.contains(info)
|| (!sender.hasPermission("citizens.admin") && !sender.hasPermission(command.permission())))
continue;
lines.add(format(command, baseCommand));
if (command.modifiers().length > 0) {
processed.add(info);
}
}
Collections.sort(lines);
return lines;
}
private String getUsage(String[] args, Command cmd) {
return new StringBuilder("/").append(args[0] + " ").append(cmd.usage()).toString();
}
/**
* Checks to see whether there is a command handler for the given command at the root level. This will check aliases
* as well.
*
* @param cmd
* The command to check
* @param modifier
* The modifier to check (may be empty)
* @return Whether the command is handled
*/
public boolean hasCommand(org.bukkit.command.Command cmd, String... modifier) {
String cmdName = cmd.getName().toLowerCase();
String[] parts = new String[modifier.length + 1];
System.arraycopy(modifier, 0, parts, 1, modifier.length);
parts[0] = cmdName;
return hasCommand(parts);
}
/**
* Checks to see whether there is a command handler for the given command parts at the root level. This will check
* aliases as well.
*
* @param parts
* The parts to check (must not be empty)
* @return Whether the command is handled
*/
public boolean hasCommand(String... parts) {
if (parts == null || parts.length == 0) {
throw new IllegalArgumentException("parts must not be empty");
}
return commands.containsKey(Joiner.on(' ').join(parts)) || commands.containsKey(parts[0] + " *");
}
private boolean hasPermission(CommandInfo method, CommandSender sender) {
Command cmd = method.commandAnnotation;
return cmd.permission().isEmpty() || hasPermission(sender, cmd.permission())
|| hasPermission(sender, "citizens.admin");
}
private boolean hasPermission(CommandSender sender, String perm) {
return sender.hasPermission(perm);
}
@Override
public List<String> onTabComplete(CommandSender sender, org.bukkit.command.Command command, String alias,
String[] args) {
List<String> results = new ArrayList<String>();
if (args.length <= 2 && args[0].equalsIgnoreCase("help")) {
return getCommands(command.getName().toLowerCase()).stream()
.map((info) -> info.commandAnnotation.modifiers().length > 0 ? info.commandAnnotation.modifiers()[0]
: null)
.collect(Collectors.toList());
}
if (args.length <= 1) {
String search = args.length == 1 ? args[0] : "";
for (String base : commands.keySet()) {
String[] parts = base.split(" ");
String cmd = parts[0];
if (!cmd.equalsIgnoreCase(command.getName()) || parts.length < 2)
continue;
String modifier = parts[1];
if (modifier.startsWith(search)) {
results.add(modifier);
}
}
return results;
}
CommandInfo cmd = getCommand(command.getName().toLowerCase(), args[0]);
if (cmd == null && args.length > 1) {
cmd = getCommand(command.getName().toLowerCase(), args[0], args[1]);
}
if (cmd == null) {
return results;
}
// partial parse
String[] newArgs = new String[args.length + 1];
System.arraycopy(args, 0, newArgs, 1, args.length);
newArgs[0] = command.getName().toLowerCase();
CommandContext context = new CommandContext(sender, newArgs);
results.addAll(cmd.getArgTabCompletions(context, sender, args.length - 1));
Collection<String> valueFlags = cmd.valueFlags();
String lastArg = (newArgs[newArgs.length - 1].isEmpty() && newArgs.length >= 2 ? newArgs[newArgs.length - 2]
: newArgs[newArgs.length - 1]).toLowerCase();
String hyphenStrippedArg = lastArg.replaceFirst("--", "");
if (lastArg.startsWith("--") && valueFlags.contains(hyphenStrippedArg)) {
results.addAll(cmd.getFlagTabCompletions(context, sender, hyphenStrippedArg));
} else {
for (String valueFlag : valueFlags) {
if (!context.hasValueFlag(valueFlag)) {
results.add("--" + valueFlag);
}
}
String flags = cmd.commandAnnotation.flags();
for (int i = 0; i < flags.length(); i++) {
char c = flags.charAt(i);
if (!context.hasFlag(c)) {
results.add("-" + c);
}
}
}
return results;
}
/**
* Register a class that contains commands (methods annotated with {@link Command}). If no dependency
* {@link Injector} is specified, then only static methods of the class will be registered. Otherwise, new instances
* the command class will be created and instance methods will be called.
*
* @see #setInjector(Injector)
* @param clazz
* The class to scan
*/
public void register(Class<?> clazz) {
registerMethods(clazz, null);
}
/**
* Registers an {@link CommandAnnotationProcessor} that can process annotations before a command is executed.
*
* Methods with the {@link Command} annotation will have the rest of their annotations scanned and stored if there
* is a matching {@link CommandAnnotationProcessor}. Annotations that do not have a processor are discarded. The
* scanning method uses annotations from the declaring class as a base before narrowing using the method's
* annotations.
*
* @param processor
* The annotation processor
*/
public void registerAnnotationProcessor(CommandAnnotationProcessor processor) {
annotationProcessors.put(processor.getAnnotationClass(), processor);
}
/*
* Register the methods of a class. This will automatically construct
* instances as necessary.
*/
private void registerMethods(Class<?> clazz, Method parent) {
Object obj = injector != null ? injector.getInstance(clazz) : null;
registerMethods(clazz, parent, obj);
}
// Register the methods of a class.
private void registerMethods(Class<?> clazz, Method parent, Object obj) {
for (Method method : clazz.getMethods()) {
if (!method.isAnnotationPresent(Command.class))
continue;
if (!Modifier.isStatic(method.getModifiers()) && obj == null)
continue;
Command cmd = method.getAnnotation(Command.class);
CommandInfo info = new CommandInfo(cmd, method);
info.instance = obj;
List<Annotation> annotations = Lists.newArrayList();
for (Annotation annotation : method.getDeclaringClass().getAnnotations()) {
Class<? extends Annotation> annotationClass = annotation.annotationType();
if (annotationProcessors.containsKey(annotationClass)) {
annotations.add(annotation);
}
}
for (Annotation annotation : method.getAnnotations()) {
Class<? extends Annotation> annotationClass = annotation.annotationType();
if (!annotationProcessors.containsKey(annotationClass))
continue;
Iterator<Annotation> itr = annotations.iterator();
while (itr.hasNext()) {
Annotation previous = itr.next();
if (previous.annotationType() == annotationClass) {
itr.remove();
}
}
annotations.add(annotation);
}
if (annotations.size() > 0) {
info.annotations = annotations;
}
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length <= 1 || parameterTypes[1] == CommandSender.class) {
info.serverCommand = true;
}
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
for (Annotation ann : parameters[i].getAnnotations()) {
if (ann instanceof Flag) {
info.addFlagAnnotation(i, parameterTypes[i], (Flag) ann);
} else if (ann instanceof Arg) {
info.addArgAnnotation(i, parameterTypes[i], (Arg) ann);
}
}
}
for (String alias : cmd.aliases()) {
for (String modifier : cmd.modifiers()) {
commands.put(alias + " " + modifier, info);
}
if (!commands.containsKey(alias + " help")) {
commands.put(alias + " help", null);
}
}
}
}
public void registerTabCompletion(JavaPlugin plugin) {
for (String string : commands.keySet()) {
PluginCommand command = plugin.getCommand(string.split(" ")[0]);
if (command == null) {
continue;
}
command.setTabCompleter(this);
}
}
private void sendHelp(CommandSender sender, String name, int page) throws CommandException {
if (name.equalsIgnoreCase("npc")) {
name = "NPC";
}
Paginator paginator = new Paginator()
.header(capitalize(name) + " " + Messaging.tr(CommandMessages.COMMAND_HELP_HEADER))
.console(sender instanceof ConsoleCommandSender);
for (String line : getLines(sender, name.toLowerCase())) {
paginator.addLine(line);
}
if (!paginator.sendPage(sender, page)) {
throw new CommandException(CommandMessages.COMMAND_PAGE_MISSING, page);
}
}
private void sendSpecificHelp(CommandSender sender, String rootCommand, String modifier) throws CommandException {
CommandInfo info = getCommand(rootCommand, modifier);
if (info == null)
throw new CommandException(CommandMessages.COMMAND_MISSING, rootCommand + " " + modifier);
Messaging.send(sender, format(info.getCommandAnnotation(), rootCommand));
String help = Messaging.tryTranslate(info.getCommandAnnotation().help());
if (help.isEmpty())
return;
Messaging.send(sender, "<aqua>" + help);
}
public void setInjector(Injector injector) {
this.injector = injector;
}
public class CommandInfo {
private List<Annotation> annotations = Lists.newArrayList();
private final Command commandAnnotation;
public Object instance;
private final Method method;
private final Map<Integer, InjectedCommandArgument> methodArguments = Maps.newHashMap();
public boolean serverCommand;
private Collection<String> valueFlags;
public CommandInfo(Command commandAnnotation, Method method) {
this.commandAnnotation = commandAnnotation;
this.method = method;
}
public void addArgAnnotation(int idx, Class<?> paramType, Arg arg) {
this.methodArguments.put(idx, new InjectedCommandArgument(injector, paramType, arg));
}
public void addFlagAnnotation(int idx, Class<?> paramType, Flag flag) {
this.methodArguments.put(idx, new InjectedCommandArgument(injector, paramType, flag));
}
private Collection<String> calculateValueFlags() {
valueFlags = new HashSet<String>();
for (InjectedCommandArgument instance : methodArguments.values()) {
instance.getValueFlag().ifPresent((flag) -> valueFlags.add(flag));
}
valueFlags.addAll(Arrays.asList(commandAnnotation.valueFlags()));
return valueFlags;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
CommandInfo other = (CommandInfo) obj;
if (commandAnnotation == null) {
if (other.commandAnnotation != null) {
return false;
}
} else if (!commandAnnotation.equals(other.commandAnnotation)) {
return false;
}
return true;
}
public Collection<? extends String> getArgTabCompletions(CommandContext args, CommandSender sender, int index) {
List<String> completions = Lists.newArrayList();
for (InjectedCommandArgument instance : methodArguments.values()) {
if (instance.matches(index)) {
String needle = index < args.argsLength() ? args.getString(index) : "";
completions.addAll(Collections2.filter(instance.getTabCompletions(args, sender),
(s) -> needle.isEmpty() || s.toLowerCase().startsWith(needle.toLowerCase())));
}
}
return completions;
}
public Command getCommandAnnotation() {
return commandAnnotation;
}
public Collection<String> getFlagTabCompletions(CommandContext args, CommandSender sender, String flag) {
List<String> completions = Lists.newArrayList();
for (InjectedCommandArgument instance : methodArguments.values()) {
if (instance.matches(flag)) {
String needle = args.getFlag(flag, "");
completions.addAll(Collections2.filter(instance.getTabCompletions(args, sender),
(s) -> needle.isEmpty() || s.toLowerCase().startsWith(needle.toLowerCase())));
}
}
return completions;
}
@Override
public int hashCode() {
return 31 + ((commandAnnotation == null) ? 0 : commandAnnotation.hashCode());
}
public Collection<String> valueFlags() {
return valueFlags == null ? calculateValueFlags() : valueFlags;
}
}
private static class InjectedCommandArgument {
private final String[] completions;
private CompletionsProvider completionsProvider;
private final String defaultValue;
private int index = -1;
private final String[] names;
private final Class<?> paramType;
private FlagValidator<?> validator;
public InjectedCommandArgument(Injector injector, Class<?> paramType, Arg arg) {
this.paramType = paramType;
this.names = new String[] {};
this.index = arg.value();
this.completions = arg.completions();
this.defaultValue = arg.defValue().isEmpty() ? null : arg.defValue();
if (arg.validator() != FlagValidator.Identity.class) {
this.validator = (FlagValidator<?>) injector.getInstance(arg.validator());
}
if (arg.completionsProvider() != CompletionsProvider.Identity.class) {
this.completionsProvider = (CompletionsProvider) injector.getInstance(arg.completionsProvider());
}
}
public InjectedCommandArgument(Injector injector, Class<?> paramType, Flag flag) {
this.paramType = paramType;
this.names = flag.value();
for (int i = 0; i < this.names.length; i++) {
this.names[i] = this.names[i].toLowerCase();
}
this.completions = flag.completions();
this.defaultValue = flag.defValue().isEmpty() ? null : flag.defValue();
if (flag.validator() != FlagValidator.Identity.class) {
this.validator = (FlagValidator<?>) injector.getInstance(flag.validator());
}
if (flag.completionsProvider() != CompletionsProvider.Identity.class) {
this.completionsProvider = (CompletionsProvider) injector.getInstance(flag.completionsProvider());
}
}
public Object getInput(CommandContext context) {
if (names.length > 0) {
String flag = names[0];
Object val = context.getFlag(flag, defaultValue);
if (val == null && names.length > 1 && !names[1].isEmpty()) {
val = context.getFlag(names[1], defaultValue);
}
return val;
} else {
return context.getString(index, defaultValue);
}
}
@SuppressWarnings("rawtypes")
private Collection<String> getTabCompletions(CommandContext args, CommandSender sender) {
if (completionsProvider != null) {
return completionsProvider.getCompletions(args, sender);
}
if (completions.length > 0) {
return Arrays.asList(completions);
}
if (Enum.class.isAssignableFrom(paramType)) {
Enum[] constants = (Enum[]) paramType.getEnumConstants();
return Lists.transform(Arrays.asList(constants), (e) -> e.name());
} else if (paramType == boolean.class || paramType == Boolean.class) {
return Arrays.asList("true", "false");
}
return Collections.emptyList();
}
public Optional<String> getValueFlag() {
return names.length == 0 ? Optional.empty() : Optional.of(names[0]);
}
public boolean matches(int index) {
return this.index == index;
}
public boolean matches(String flag) {
return names.length > 0
&& (names[0].equalsIgnoreCase(flag) || (names.length > 1 && names[1].equalsIgnoreCase(flag)));
}
}
private static String capitalize(Object string) {
String capitalize = string.toString();
return capitalize.length() == 0 ? ""
: Character.toUpperCase(capitalize.charAt(0)) + capitalize.substring(1, capitalize.length());
}
private static String format(Command command, String alias) {
return String.format(COMMAND_FORMAT, alias, (command.usage().isEmpty() ? "" : " " + command.usage()),
Messaging.tryTranslate(command.desc()));
}
private static int getLevenshteinDistance(String s, String t) {
if (s == null || t == null)
throw new IllegalArgumentException("Strings must not be null");
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0)
return m;
else if (m == 0)
return n;
int p[] = new int[n + 1]; // 'previous' cost array, horizontally
int d[] = new int[n + 1]; // cost array, horizontally
int _d[]; // placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i <= n; i++)
p[i] = i;
for (j = 1; j <= m; j++) {
t_j = t.charAt(j - 1);
d[0] = j;
for (i = 1; i <= n; i++) {
cost = s.charAt(i - 1) == t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left
// and up +cost
d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
private static <T extends Enum<?>> T matchEnum(T[] values, String toMatch) {
toMatch = toMatch.toLowerCase().replace('-', '_').replace(' ', '_');
for (T check : values) {
if (toMatch.equals(check.name().toLowerCase())
|| (toMatch.equals("item") && check == EntityType.DROPPED_ITEM)) {
return check; // check for an exact match first
}
}
for (T check : values) {
String name = check.name().toLowerCase();
if (name.replace("_", "").equals(toMatch) || name.startsWith(toMatch)) {
return check;
}
}
return null;
}
private static final String COMMAND_FORMAT = "<green>/{{%s%s <green>- [[%s";
// Logger for general errors.
private static final Logger logger = Logger.getLogger(CommandManager.class.getCanonicalName());
}