58 lines
1.8 KiB
Java
58 lines
1.8 KiB
Java
package io.gitlab.jfronny.inceptum.cli;
|
|
|
|
import java.util.*;
|
|
|
|
public abstract class Command {
|
|
private final String help;
|
|
private final String usage;
|
|
private final List<String> aliases;
|
|
private final Collection<Command> subCommands;
|
|
|
|
public Command(String help, String usage, String... aliases) {
|
|
this(help, usage, Arrays.asList(aliases), List.of());
|
|
}
|
|
|
|
public Command(String help, String usage, List<String> aliases, List<Command> subCommands) {
|
|
this.help = help;
|
|
this.usage = usage;
|
|
this.aliases = List.copyOf(aliases);
|
|
this.subCommands = List.copyOf(subCommands);
|
|
}
|
|
|
|
public boolean isAlias(String text) {
|
|
return aliases.contains(text.replaceAll("^[-/]*", "").toLowerCase(Locale.ROOT));
|
|
}
|
|
|
|
public String getName() {
|
|
return aliases.get(0);
|
|
}
|
|
|
|
public boolean enableLog() {
|
|
return false;
|
|
}
|
|
|
|
protected abstract void invoke(CommandArgs args) throws Exception;
|
|
|
|
public CommandResolution resolve(CommandArgs args) {
|
|
if (args.length != 0) {
|
|
for (Command command : subCommands) {
|
|
if (command.isAlias(args.get(0))) {
|
|
CommandResolution resolution = command.resolve(args.subArgs());
|
|
if (!aliases.isEmpty()) resolution.resolvePath().add(0, aliases.get(0));
|
|
return resolution;
|
|
}
|
|
}
|
|
}
|
|
return new CommandResolution(this, args, aliases.isEmpty()
|
|
? new ArrayList<>()
|
|
: new ArrayList<>(List.of(aliases.get(0))));
|
|
}
|
|
|
|
public void buildHelp(HelpBuilder builder) {
|
|
builder.writeCommand(aliases, help, usage);
|
|
for (Command command : subCommands) {
|
|
command.buildHelp(aliases.isEmpty() ? builder : builder.beginSubcommand(aliases.get(0)));
|
|
}
|
|
}
|
|
}
|