Inceptum/src/main/java/io/gitlab/jfronny/inceptum/cli/Command.java

57 lines
1.7 KiB
Java
Raw Normal View History

2021-10-30 22:05:24 +02:00
package io.gitlab.jfronny.inceptum.cli;
import java.util.*;
2021-10-30 22:05:24 +02:00
public abstract class Command {
private final String help;
private final List<String> aliases;
private final Collection<Command> subCommands;
2021-10-30 22:05:24 +02:00
public Command(String help, String... aliases) {
this(help, Arrays.asList(aliases), List.of());
}
public Command(String help, List<String> aliases, List<Command> subCommands) {
2021-10-30 22:05:24 +02:00
this.help = help;
this.aliases = List.copyOf(aliases);
this.subCommands = List.copyOf(subCommands);
2021-10-30 22:05:24 +02:00
}
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);
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);
for (Command command : subCommands) {
command.buildHelp(builder.beginSubcommand());
}
}
2021-10-30 22:05:24 +02:00
}