package edu.brown.cs.student.term.repl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * REPL Class maps input to proper class and function for that command. */ public class REPL { private Map commands; /** * Constructor for a REPL object. * @param userCommands - map of string to Command object for REPL to run */ public REPL(HashMap userCommands) { commands = userCommands; } /** * Gets the current map of commands the REPL supports. * @return the command map */ public Map getReplCommandMap() { return commands; } /** * Reads user input, maps it to the correct command, and continues. */ public void runREPL() { BufferedReader commandHandler = new BufferedReader(new InputStreamReader(System.in)); try { String command = commandHandler.readLine(); while (command != null) { String[] commandPieces = command.split("\\s+(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); if (commands.containsKey(commandPieces[0])) { Command desiredCommand = commands.get(commandPieces[0]); String[] arguments = Arrays.copyOfRange(commandPieces, 1, commandPieces.length); desiredCommand.run(arguments); } else { System.out.println("ERROR: Sorry, command not recognized! Please try again."); } command = commandHandler.readLine(); } } catch (IOException e) { //might wanna change this later System.out.println("ERROR: Could not locate specified file!"); } } }