2021-10-30 22:05:24 +02:00
|
|
|
package io.gitlab.jfronny.inceptum.cli;
|
|
|
|
|
2022-01-04 17:48:01 +01:00
|
|
|
import java.util.*;
|
2021-10-30 22:05:24 +02:00
|
|
|
|
|
|
|
public abstract class Command {
|
|
|
|
private final String help;
|
|
|
|
private final List<String> aliases;
|
2022-01-04 17:48:01 +01:00
|
|
|
private final Collection<Command> subCommands;
|
2021-10-30 22:05:24 +02:00
|
|
|
|
|
|
|
public Command(String help, String... aliases) {
|
2022-01-04 17:48:01 +01:00
|
|
|
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;
|
2022-01-04 17:48:01 +01:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2022-01-04 17:48:01 +01:00
|
|
|
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
|
|
|
}
|