1 /* 2 * Copyright (c) 2020 Helmut Neemann. 3 * Use of this source code is governed by the GPL v3 license 4 * that can be found in the LICENSE file. 5 */ 6 package de.neemann.digital.cli.cli; 7 8 import de.neemann.digital.lang.Lang; 9 10 import java.io.IOException; 11 import java.io.PrintStream; 12 import java.io.Writer; 13 import java.util.Arrays; 14 import java.util.HashMap; 15 16 /** 17 * The command muxer 18 */ 19 public class Muxer extends NamedCommand { 20 private final HashMap<String, CLICommand> commands; 21 22 /** 23 * Creates a new muxer 24 * 25 * @param name the name of the muxer 26 */ Muxer(String name)27 public Muxer(String name) { 28 super(name); 29 this.commands = new HashMap<>(); 30 } 31 32 /** 33 * Adds a command to the muxer 34 * 35 * @param command the command 36 * @return this for chained calls 37 */ addCommand(NamedCommand command)38 public Muxer addCommand(NamedCommand command) { 39 return addCommand(command.getName(), command); 40 } 41 42 /** 43 * Adds a command to the muxer 44 * 45 * @param name the name of the command 46 * @param command the command 47 * @return this for chained calls 48 */ addCommand(String name, CLICommand command)49 public Muxer addCommand(String name, CLICommand command) { 50 commands.put(name, command); 51 return this; 52 } 53 54 @Override printDescription(PrintStream out, String prefix)55 public void printDescription(PrintStream out, String prefix) { 56 out.print(prefix); 57 out.print(getName()); 58 out.println(); 59 for (CLICommand c : commands.values()) 60 c.printDescription(out, prefix + " "); 61 } 62 63 @Override printXMLDescription(Writer w)64 public void printXMLDescription(Writer w) throws IOException { 65 w.write("<indent>\n"); 66 w.write(getName()); 67 for (CLICommand c : commands.values()) 68 c.printXMLDescription(w); 69 w.write("</indent>\n"); 70 } 71 72 @Override execute(String[] args)73 public void execute(String[] args) throws CLIException { 74 if (args.length == 0) 75 throw new CLIException(Lang.get("cli_notEnoughArgumentsGiven"), 100); 76 77 CLICommand command = commands.get(args[0]); 78 if (command == null) 79 throw new CLIException(Lang.get("cli_command_N_hasNoSubCommand_N", getName(), args[0]), 101); 80 81 command.execute(Arrays.copyOfRange(args, 1, args.length)); 82 } 83 84 } 85