From 92c8eae71fd662c2b7e76b17309c1b2f91c38d41 Mon Sep 17 00:00:00 2001 From: Sam Anthony Date: Mon, 2 Dec 2024 17:12:19 -0500 Subject: client cli --- src/main/java/derms/client/CLI.java | 86 +++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/main/java/derms/client/CLI.java (limited to 'src/main/java/derms/client/CLI.java') diff --git a/src/main/java/derms/client/CLI.java b/src/main/java/derms/client/CLI.java new file mode 100644 index 0000000..05f4e35 --- /dev/null +++ b/src/main/java/derms/client/CLI.java @@ -0,0 +1,86 @@ +package derms.client; + +import java.util.*; + +abstract class CLI implements Runnable { + protected Map commands = new HashMap(); + protected List cmdDescriptions = new ArrayList(); + protected List argDescriptions = new ArrayList(); + + protected CLI() { + commands.put("quit", new Quit()); + cmdDescriptions.add(new Description("quit", "Exit the program")); + + commands.put("help", new Help()); + cmdDescriptions.add(new Description("help", "List commands")); + } + + @Override + public void run() { + Scanner scanner = new Scanner(System.in); + System.out.println("Type 'help' for a list of commands."); + for (;;) { + System.out.print("Command: "); + String input = scanner.nextLine(); + String[] fields = input.split(" "); + if (fields.length < 1 || fields[0] == "") { + continue; + } + Command cmd = commands.get(fields[0]); + if (cmd == null) { + System.out.println("Invalid command '"+fields[0]+"'"); + System.out.println("Type 'help' for a list of commands."); + continue; + } + String[] args = null; + if (fields.length < 2) { + args = new String[0]; + } else { + args = Arrays.copyOfRange(fields, 1, fields.length); + } + cmd.exec(args); + } + } + + protected interface Command { + public void exec(String[] args); + } + + protected class Quit implements Command { + @Override + public void exec(String[] args) { + System.out.println("Shutting down..."); + System.exit(1); + } + } + + protected class Help implements Command { + @Override + public void exec(String[] args) { + System.out.println("\nCommands:"); + for (Description d : cmdDescriptions) { + System.out.println(d); + } + System.out.println("\nArguments:"); + for (Description d : argDescriptions) { + System.out.println(d); + } + System.out.println(); + } + } + + protected class Description { + String object; /// The thing being described + String description; + + protected Description(String object, String description) { + this.object = object; + this.description = description; + } + + @Override + public String toString() { + return object+"\n\t"+description; + } + } +} -- cgit v1.2.3