package io.gitlab.jfronny.inceptum.frontend.cli; import io.gitlab.jfronny.inceptum.model.inceptum.InstanceMeta; import io.gitlab.jfronny.inceptum.util.MetaHolder; import io.gitlab.jfronny.inceptum.util.Utils; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; public abstract class BaseInstanceCommand extends Command { public BaseInstanceCommand(String help, String usage, String... aliases) { super(help, mutateUsage(usage), aliases); } public BaseInstanceCommand(String help, String usage, List aliases, List subCommands) { super(help, mutateUsage(usage), aliases, subCommands); } private static String mutateUsage(String usage) { StringBuilder sb = new StringBuilder(); for (String s : usage.split("\n")) { if (s.isBlank()) sb.append("\n"); else sb.append("\n ").append(s); } return sb.substring(1); } @Override protected void invoke(CommandArgs args) { if (args.length == 0) { Utils.LOGGER.error("You must specify an instance to commit in"); return; } Path instancePath = MetaHolder.INSTANCE_DIR.resolve(args.get(0)); Path instanceMetaPath = instancePath.resolve("instance.json"); if (!Files.exists(instanceMetaPath)) { Utils.LOGGER.error("Invalid instance: \"" + args.get(0) + "\""); return; } InstanceMeta meta; try { meta = Utils.loadObject(instanceMetaPath, InstanceMeta.class); } catch (IOException e) { Utils.LOGGER.error("Could not read instance metadata", e); return; } try { invoke(args.subArgs(), instancePath, meta); } catch (Exception e) { Utils.LOGGER.error("Could not execute command", e); return; } } protected abstract void invoke(CommandArgs args, Path instancePath, InstanceMeta meta) throws Exception; }