package io.gitlab.jfronny.inceptum.cli; import java.util.*; public abstract class Command { private final String help; private final List aliases; private final Collection subCommands; public Command(String help, String... aliases) { this(help, Arrays.asList(aliases), List.of()); } public Command(String help, List aliases, List subCommands) { this.help = help; 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); 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()); } } }