diff options
| author | Ben Culkin <scorpress@gmail.com> | 2020-04-13 18:40:41 -0400 |
|---|---|---|
| committer | Ben Culkin <scorpress@gmail.com> | 2020-04-13 18:40:41 -0400 |
| commit | d4ca769e542b2489b1e23cfcbdc3a0b7275b87cd (patch) | |
| tree | 1653a7399f97fb0c63ce62e3f60fd830d5c37f70 /base/src/main/java/bjc/utils/cli | |
| parent | 2ac2e31a56ae59ee582e43a90c3495f86dd9ee7a (diff) | |
Cleanup pass
Cleanup pass to uniformize things
Diffstat (limited to 'base/src/main/java/bjc/utils/cli')
12 files changed, 324 insertions, 275 deletions
diff --git a/base/src/main/java/bjc/utils/cli/CLICommander.java b/base/src/main/java/bjc/utils/cli/CLICommander.java index ad3bea9..f27454e 100644 --- a/base/src/main/java/bjc/utils/cli/CLICommander.java +++ b/base/src/main/java/bjc/utils/cli/CLICommander.java @@ -24,20 +24,22 @@ public class CLICommander { * Create a new CLI interface powered by streams. * * @param input - * The stream to get user input from. + * The stream to get user input from. * * @param output - * The stream to send normal output to. + * The stream to send normal output to. * * @param error - * The stream to send error output to. + * The stream to send error output to. */ - public CLICommander(final InputStream input, final OutputStream output, final OutputStream error) { - if(input == null) + public CLICommander(final InputStream input, final OutputStream output, + final OutputStream error) { + if (input == null) throw new NullPointerException("Input stream must not be null"); - else if(output == null) + else if (output == null) throw new NullPointerException("Output stream must not be null"); - else if(error == null) throw new NullPointerException("Error stream must not be null"); + else if (error == null) + throw new NullPointerException("Error stream must not be null"); this.input = input; this.output = output; @@ -53,9 +55,8 @@ public class CLICommander { /* * Set up input streams. * - * We're suppressing the warning about a potentially leaked - * resource because we might use the input stream multiple - * times. + * We're suppressing the warning about a potentially leaked resource because we + * might use the input stream multiple times. */ @SuppressWarnings("resource") final Scanner inputSource = new Scanner(input); @@ -63,24 +64,23 @@ public class CLICommander { /* * The mode currently being used to handle commands. * - * Used to preserve the initial mode, so that a mode can be - * invoked more than once. + * Used to preserve the initial mode, so that a mode can be invoked more than + * once. */ CommandMode currentMode = initialMode; /* The number of the command we are executing. */ int comno = 1; /* - * Process commands until we're told to stop, by the mode being - * set to null. + * Process commands until we're told to stop, by the mode being set to null. */ - while(currentMode != null) { + while (currentMode != null) { /* * Print out the command prompt. * * Use a custom prompt if one is specified. */ - if(currentMode.isCustomPromptEnabled()) { + if (currentMode.isCustomPromptEnabled()) { normalOutput.print(currentMode.getCustomPrompt()); } else { normalOutput.printf("%s (%d)>> ", currentMode.getName(), comno); @@ -92,21 +92,22 @@ public class CLICommander { final String currentLine = inputSource.nextLine(); /* Handle commands we can handle in this mode. */ - if(currentMode.canHandle(currentLine)) { + if (currentMode.canHandle(currentLine)) { final String[] commandTokens = currentLine.split(" "); String[] commandArgs = null; final int argCount = commandTokens.length; /* Parse args if they are present. */ - if(argCount > 1) { + if (argCount > 1) { commandArgs = Arrays.copyOfRange(commandTokens, 1, argCount); } /* Process command. */ currentMode = currentMode.process(commandTokens[0], commandArgs); } else { - errorOutput.printf("Error: Unrecognized command '%s' (no. %d)\n", currentLine, comno); + errorOutput.printf("Error: Unrecognized command '%s' (no. %d)\n", + currentLine, comno); } } @@ -117,10 +118,11 @@ public class CLICommander { * Set the initial command mode to use. * * @param initialMode - * The initial command mode to use. + * The initial command mode to use. */ public void setInitialCommandMode(final CommandMode initialMode) { - if(initialMode == null) throw new NullPointerException("Initial mode must be non-null"); + if (initialMode == null) + throw new NullPointerException("Initial mode must be non-null"); this.initialMode = initialMode; } diff --git a/base/src/main/java/bjc/utils/cli/CommandHandler.java b/base/src/main/java/bjc/utils/cli/CommandHandler.java index 6cc2d68..2e78f1b 100644 --- a/base/src/main/java/bjc/utils/cli/CommandHandler.java +++ b/base/src/main/java/bjc/utils/cli/CommandHandler.java @@ -13,10 +13,10 @@ public interface CommandHandler extends Function<String[], CommandMode> { * Execute this command. * * @param args - * The arguments for this command. + * The arguments for this command. * - * @return The command mode to switch to after this command, or null to - * stop executing commands. + * @return The command mode to switch to after this command, or null to stop + * executing commands. */ default CommandMode handle(final String[] args) { return this.apply(args); diff --git a/base/src/main/java/bjc/utils/cli/CommandHelp.java b/base/src/main/java/bjc/utils/cli/CommandHelp.java index 97d7dad..d07c9d5 100644 --- a/base/src/main/java/bjc/utils/cli/CommandHelp.java +++ b/base/src/main/java/bjc/utils/cli/CommandHelp.java @@ -17,11 +17,11 @@ public interface CommandHelp { * Get the summary line for a command. * * A summary line should consist of a string of the following format - * + * * <pre> * "<command-name&rt;\t<command-summary&rt;" * </pre> - * + * * where anything in angle brackets should be filled in. * * @return The summary line line for a command diff --git a/base/src/main/java/bjc/utils/cli/CommandMode.java b/base/src/main/java/bjc/utils/cli/CommandMode.java index b33077b..c145c1c 100644 --- a/base/src/main/java/bjc/utils/cli/CommandMode.java +++ b/base/src/main/java/bjc/utils/cli/CommandMode.java @@ -11,10 +11,10 @@ public interface CommandMode extends Comparable<CommandMode> { * Check to see if this mode can handle the specified command. * * @param command - * The command to check. + * The command to check. * - * @return Whether or not this mode can handle the command. It is - * assumed not by default. + * @return Whether or not this mode can handle the command. It is assumed not by + * default. */ default boolean canHandle(final String command) { return false; @@ -26,17 +26,19 @@ public interface CommandMode extends Comparable<CommandMode> { * @return The custom prompt for this mode. * * @throws UnsupportedOperationException - * If this mode doesn't support a custom prompt. + * If this mode doesn't support a custom + * prompt. */ default String getCustomPrompt() { - throw new UnsupportedOperationException("This mode doesn't support a custom prompt"); + throw new UnsupportedOperationException( + "This mode doesn't support a custom prompt"); } /** * Get the name of this command mode. * - * @return The name of this command mode, or a default string if one - * isn't specified. + * @return The name of this command mode, or a default string if one isn't + * specified. */ public default String getName() { return "(anonymous)"; @@ -55,13 +57,13 @@ public interface CommandMode extends Comparable<CommandMode> { * Process a command in this mode.. * * @param command - * The command to process. + * The command to process. * * @param args - * A list of arguments to the command. + * A list of arguments to the command. * - * @return The command mode to use for the next command. Defaults to - * doing nothing, and staying in the current mode. + * @return The command mode to use for the next command. Defaults to doing + * nothing, and staying in the current mode. */ default CommandMode process(final String command, final String[] args) { return this; diff --git a/base/src/main/java/bjc/utils/cli/DelegatingCommand.java b/base/src/main/java/bjc/utils/cli/DelegatingCommand.java index ff981bd..f17b6b5 100644 --- a/base/src/main/java/bjc/utils/cli/DelegatingCommand.java +++ b/base/src/main/java/bjc/utils/cli/DelegatingCommand.java @@ -13,7 +13,7 @@ class DelegatingCommand implements Command { * Create a new command that delegates to another command. * * @param delegate - * The command to delegate to. + * The command to delegate to. */ public DelegatingCommand(final Command delegate) { this.delegate = delegate; diff --git a/base/src/main/java/bjc/utils/cli/GenericCommand.java b/base/src/main/java/bjc/utils/cli/GenericCommand.java index bb624cd..a847bea 100644 --- a/base/src/main/java/bjc/utils/cli/GenericCommand.java +++ b/base/src/main/java/bjc/utils/cli/GenericCommand.java @@ -16,22 +16,25 @@ public class GenericCommand implements Command { * Create a new generic command. * * @param handler - * The handler to use for the command. + * The handler to use for the command. * * @param description - * The description of the command. May be null, in which case a - * default is provided. + * The description of the command. May be null, in which case + * a default is provided. * * @param help - * The detailed help message for the command. May be null, in - * which case the description is repeated for the detailed help. + * The detailed help message for the command. May be null, in + * which case the description is repeated for the detailed + * help. */ - public GenericCommand(final CommandHandler handler, final String description, final String help) { - if(handler == null) throw new NullPointerException("Command handler must not be null"); + public GenericCommand(final CommandHandler handler, final String description, + final String help) { + if (handler == null) + throw new NullPointerException("Command handler must not be null"); this.handler = handler; - if(description == null) { + if (description == null) { this.help = new NullHelp(); } else { this.help = new GenericHelp(description, help); diff --git a/base/src/main/java/bjc/utils/cli/GenericCommandMode.java b/base/src/main/java/bjc/utils/cli/GenericCommandMode.java index 79e716f..5058af6 100644 --- a/base/src/main/java/bjc/utils/cli/GenericCommandMode.java +++ b/base/src/main/java/bjc/utils/cli/GenericCommandMode.java @@ -42,15 +42,17 @@ public class GenericCommandMode implements CommandMode { * Create a new generic command mode * * @param normalOutput - * The function to use for normal output. + * The function to use for normal output. * * @param errorOutput - * The function to use for error output. + * The function to use for error output. */ - public GenericCommandMode(final Consumer<String> normalOutput, final Consumer<String> errorOutput) { - if(normalOutput == null) + public GenericCommandMode(final Consumer<String> normalOutput, + final Consumer<String> errorOutput) { + if (normalOutput == null) throw new NullPointerException("Normal output source must be non-null"); - else if(errorOutput == null) throw new NullPointerException("Error output source must be non-null"); + else if (errorOutput == null) + throw new NullPointerException("Error output source must be non-null"); this.normalOutput = normalOutput; this.errorOutput = errorOutput; @@ -68,33 +70,38 @@ public class GenericCommandMode implements CommandMode { * Add an alias to an existing command. * * @param commandName - * The name of the command to add an alias for. + * The name of the command to add an alias for. * * @param aliasName - * The new alias for the command. + * The new alias for the command. * * @throws IllegalArgumentException - * If the specified command doesn't have a bound handler, or if - * the alias name already has a bound value. + * If the specified command doesn't have a + * bound handler, or if the alias name already + * has a bound value. */ public void addCommandAlias(final String commandName, final String aliasName) { - if(commandName == null) { + if (commandName == null) { throw new NullPointerException("Command name must not be null"); - } else if(aliasName == null) { + } else if (aliasName == null) { String msg = "Alias name must not be null"; throw new NullPointerException(msg); - } else if(!commandHandlers.containsKey(commandName) && !defaultHandlers.containsKey(commandName)) { - String msg = String.format("Cannot alias non-existant command '%s'", commandName); + } else if (!commandHandlers.containsKey(commandName) + && !defaultHandlers.containsKey(commandName)) { + String msg = String.format("Cannot alias non-existant command '%s'", + commandName); throw new IllegalArgumentException(msg); - } else if(commandHandlers.containsKey(aliasName) || defaultHandlers.containsKey(aliasName)) { - String msg = String.format("Cannot bind alias '%s' to an already bound command.", aliasName); + } else if (commandHandlers.containsKey(aliasName) + || defaultHandlers.containsKey(aliasName)) { + String msg = String.format( + "Cannot bind alias '%s' to an already bound command.", aliasName); throw new IllegalArgumentException(msg); } else { /* The command that will be aliased. */ Command aliasedCommand; /* Get the alias. */ - if(defaultHandlers.containsKey(commandName)) { + if (defaultHandlers.containsKey(commandName)) { aliasedCommand = defaultHandlers.get(commandName).aliased(); } else { aliasedCommand = commandHandlers.get(commandName).aliased(); @@ -108,20 +115,21 @@ public class GenericCommandMode implements CommandMode { * Add a command to this command mode. * * @param command - * The name of the command to add. + * The name of the command to add. * * @param handler - * The handler to use for the specified command. + * The handler to use for the specified command. * * @throws IllegalArgumentException - * If the specified command already has a handler registered. + * If the specified command already has a + * handler registered. */ public void addCommandHandler(final String command, final Command handler) { - if(command == null) { + if (command == null) { throw new NullPointerException("Command must not be null"); - } else if(handler == null) { + } else if (handler == null) { throw new NullPointerException("Handler must not be null"); - } else if(canHandle(command)) { + } else if (canHandle(command)) { String msg = String.format("Command '%s' already has a registered handler"); throw new IllegalArgumentException(msg); } else { @@ -133,10 +141,10 @@ public class GenericCommandMode implements CommandMode { * Add a help topic to this command mode that isn't tied to a command. * * @param topicName - * The name of the topic. + * The name of the topic. * * @param topic - * The contents of the topic. + * The contents of the topic. */ public void addHelpTopic(final String topicName, final CommandHelp topic) { helpTopics.put(topicName, topic); @@ -146,8 +154,8 @@ public class GenericCommandMode implements CommandMode { /* * @TODO 10/09/17 Ben Culkin :CommandExtraction * - * These command messages should be extracted into some kind of - * file-based abstraction. + * These command messages should be extracted into some kind of file-based + * abstraction. */ private GenericCommand buildAliasCommand() { final String aliasShortHelp = "alias\tAlias one command to another"; @@ -155,7 +163,7 @@ public class GenericCommandMode implements CommandMode { + " Invoke with two arguments: the name of the command to alias" + "followed by the name of the alias to give that command."; - return new GenericCommand((args) -> { + return new GenericCommand(args -> { doAliasCommands(args); return this; @@ -164,9 +172,10 @@ public class GenericCommandMode implements CommandMode { private GenericCommand buildClearCommands() { final String clearShortHelp = "clear\tClear the screen"; - final String clearLongHelp = "Clears the screen of all the text on it," + " and prints a new prompt."; + final String clearLongHelp = "Clears the screen of all the text on it," + + " and prints a new prompt."; - return new GenericCommand((args) -> { + return new GenericCommand(args -> { errorOutput.accept("ERROR: This console doesn't support screen clearing"); return this; @@ -178,7 +187,7 @@ public class GenericCommandMode implements CommandMode { final String exitLongHelp = "First prompts the user to make sure they want to" + " exit, then quits if they say they do"; - return new GenericCommand((args) -> { + return new GenericCommand(args -> { errorOutput.accept("ERROR: This console doesn't support auto-exiting"); return this; @@ -190,10 +199,11 @@ public class GenericCommandMode implements CommandMode { final String helpLongHelp = "Consults the internal help system." + " Invoked in two different ways. Invoking with no arguments" + " causes all the topics you can ask for details on to be list," - + " while invoking with the name of a topic will print the entry" + " for that topic"; + + " while invoking with the name of a topic will print the entry" + + " for that topic"; - return new GenericCommand((args) -> { - if(args == null || args.length == 0) { + return new GenericCommand(args -> { + if (args == null || args.length == 0) { /* Invoke general help */ doHelpSummary(); } else { @@ -210,7 +220,7 @@ public class GenericCommandMode implements CommandMode { final String listLongHelp = "Lists all of the commands available in this mode," + " as well as commands available in any mode"; - return new GenericCommand((args) -> { + return new GenericCommand(args -> { doListCommands(); return this; @@ -219,12 +229,13 @@ public class GenericCommandMode implements CommandMode { @Override public boolean canHandle(final String command) { - return commandHandlers.containsKey(command) || defaultHandlers.containsKey(command); + return commandHandlers.containsKey(command) + || defaultHandlers.containsKey(command); } /* Implement default commands */ private void doAliasCommands(final String[] args) { - if(args.length != 2) { + if (args.length != 2) { String msg = String.format( "ERROR: Alias requires two arguments. The command name, and the alias for that command. "); errorOutput.accept(msg); @@ -232,12 +243,14 @@ public class GenericCommandMode implements CommandMode { final String commandName = args[0]; final String aliasName = args[1]; - if(!canHandle(commandName)) { - String msg = String.format("ERROR: '%s' is not a valid command.", commandName); + if (!canHandle(commandName)) { + String msg = String.format("ERROR: '%s' is not a valid command.", + commandName); errorOutput.accept(msg); - } else if(canHandle(aliasName)) { - String msg = String.format("ERROR: Cannot overwrite command '%s'", aliasName); + } else if (canHandle(aliasName)) { + String msg = String.format("ERROR: Cannot overwrite command '%s'", + aliasName); errorOutput.accept(msg); } else { @@ -247,15 +260,17 @@ public class GenericCommandMode implements CommandMode { } private void doHelpCommand(final String commandName) { - if(commandHandlers.containsKey(commandName)) { - final String desc = commandHandlers.get(commandName).getHelp().getDescription(); + if (commandHandlers.containsKey(commandName)) { + final String desc + = commandHandlers.get(commandName).getHelp().getDescription(); normalOutput.accept("\n" + desc); - } else if(defaultHandlers.containsKey(commandName)) { - final String desc = defaultHandlers.get(commandName).getHelp().getDescription(); + } else if (defaultHandlers.containsKey(commandName)) { + final String desc + = defaultHandlers.get(commandName).getHelp().getDescription(); normalOutput.accept("\n" + desc); - } else if(helpTopics.containsKey(commandName)) { + } else if (helpTopics.containsKey(commandName)) { normalOutput.accept("\n" + helpTopics.get(commandName).getDescription()); } else { String msg = String.format("ERROR: No help available for '%s'", commandName); @@ -267,9 +282,9 @@ public class GenericCommandMode implements CommandMode { private void doHelpSummary() { normalOutput.accept("Help topics for this command mode are as follows:\n"); - if(commandHandlers.size() > 0) { + if (commandHandlers.size() > 0) { commandHandlers.forEachValue(command -> { - if(!command.isAlias()) { + if (!command.isAlias()) { String comLine = command.getHelp().getSummary(); String msg = String.format("\t%s\n", comLine); @@ -280,14 +295,14 @@ public class GenericCommandMode implements CommandMode { normalOutput.accept("\tNone available\n"); } - normalOutput.accept("\nHelp topics available in all command modes are as follows\n"); - if(defaultHandlers.size() > 0) { + normalOutput + .accept("\nHelp topics available in all command modes are as follows\n"); + if (defaultHandlers.size() > 0) { /* - * @NOTE This block here should be abstracted out into a - * method. + * @NOTE This block here should be abstracted out into a method. */ defaultHandlers.forEachValue(command -> { - if(!command.isAlias()) { + if (!command.isAlias()) { String comLine = command.getHelp().getSummary(); String msg = String.format("\t%s\n", comLine); @@ -298,8 +313,9 @@ public class GenericCommandMode implements CommandMode { normalOutput.accept("\tNone available\n"); } - normalOutput.accept("\nHelp topics not associated with a command are as follows\n"); - if(helpTopics.size() > 0) { + normalOutput + .accept("\nHelp topics not associated with a command are as follows\n"); + if (helpTopics.size() > 0) { helpTopics.forEachValue(topic -> { String msg = String.format("\t%s\n", topic.getSummary()); @@ -331,14 +347,16 @@ public class GenericCommandMode implements CommandMode { @Override public String getCustomPrompt() { - if(customPrompt != null) return customPrompt; + if (customPrompt != null) + return customPrompt; return CommandMode.super.getCustomPrompt(); } @Override public String getName() { - if(modeName != null) return modeName; + if (modeName != null) + return modeName; return CommandMode.super.getName(); } @@ -352,15 +370,16 @@ public class GenericCommandMode implements CommandMode { public CommandMode process(final String command, final String[] args) { normalOutput.accept("\n"); - if(defaultHandlers.containsKey(command)) + if (defaultHandlers.containsKey(command)) return defaultHandlers.get(command).getHandler().handle(args); - else if(commandHandlers.containsKey(command)) + else if (commandHandlers.containsKey(command)) return commandHandlers.get(command).getHandler().handle(args); else { - if(args != null) { + if (args != null) { String argString = String.join(", ", args); - String msg = String.format("ERROR: Unrecognized command %s (arguments %s)", command, - argString); + String msg + = String.format("ERROR: Unrecognized command %s (arguments %s)", + command, argString); errorOutput.accept(msg); } else { @@ -369,7 +388,7 @@ public class GenericCommandMode implements CommandMode { errorOutput.accept(msg); } - if(unknownCommandHandler == null) { + if (unknownCommandHandler == null) { String msg = String.format("Command %s is invalid", command); throw new UnsupportedOperationException(msg); @@ -385,8 +404,8 @@ public class GenericCommandMode implements CommandMode { * Set the custom prompt for this mode * * @param prompt - * The custom prompt for this mode, or null to disable the custom - * prompt + * The custom prompt for this mode, or null to disable the custom + * prompt */ public void setCustomPrompt(final String prompt) { customPrompt = prompt; @@ -396,7 +415,7 @@ public class GenericCommandMode implements CommandMode { * Set the name of this mode * * @param name - * The desired name of this mode, or null to use the default name + * The desired name of this mode, or null to use the default name */ public void setModeName(final String name) { modeName = name; @@ -406,11 +425,12 @@ public class GenericCommandMode implements CommandMode { * Set the handler to use for unknown commands * * @param handler - * The handler to use for unknown commands, or null to throw on - * unknown commands + * The handler to use for unknown commands, or null to throw on + * unknown commands */ public void setUnknownCommandHandler(final BiConsumer<String, String[]> handler) { - if(handler == null) throw new NullPointerException("Handler must not be null"); + if (handler == null) + throw new NullPointerException("Handler must not be null"); unknownCommandHandler = handler; } @@ -426,8 +446,8 @@ public class GenericCommandMode implements CommandMode { /* Add commands handled in a upper layer. */ /* - * @NOTE Figure out a place to put commands that apply across - * all modes, but only to a specific application. + * @NOTE Figure out a place to put commands that apply across all modes, but + * only to a specific application. */ defaultHandlers.put("clear", buildClearCommands()); defaultHandlers.put("exit", buildExitCommand()); @@ -443,30 +463,30 @@ public class GenericCommandMode implements CommandMode { final StringBuilder builder = new StringBuilder(); builder.append("GenericCommandMode ["); - if(commandHandlers != null) { + if (commandHandlers != null) { builder.append("commandHandlers="); builder.append(commandHandlers); } - if(defaultHandlers != null) { + if (defaultHandlers != null) { builder.append(", "); builder.append("defaultHandlers="); builder.append(defaultHandlers); } - if(helpTopics != null) { + if (helpTopics != null) { builder.append(", "); builder.append("helpTopics="); builder.append(helpTopics); } - if(modeName != null) { + if (modeName != null) { builder.append(", "); builder.append("modeName="); builder.append(modeName); } - if(customPrompt != null) { + if (customPrompt != null) { builder.append(", "); builder.append("customPrompt="); builder.append(customPrompt); diff --git a/base/src/main/java/bjc/utils/cli/GenericHelp.java b/base/src/main/java/bjc/utils/cli/GenericHelp.java index 2e74a6c..45d3a88 100644 --- a/base/src/main/java/bjc/utils/cli/GenericHelp.java +++ b/base/src/main/java/bjc/utils/cli/GenericHelp.java @@ -14,14 +14,14 @@ public class GenericHelp implements CommandHelp { * Create a new help topic. * * @param summary - * The summary of this help topic. + * The summary of this help topic. * * @param description - * The description of this help topic, or null if this help topic - * doesn't have a more detailed description. + * The description of this help topic, or null if this help + * topic doesn't have a more detailed description. */ public GenericHelp(final String summary, final String description) { - if(summary == null) { + if (summary == null) { throw new NullPointerException("Help summary must be non-null"); } @@ -31,7 +31,7 @@ public class GenericHelp implements CommandHelp { @Override public String getDescription() { - if(description == null) { + if (description == null) { return summary; } @@ -49,12 +49,12 @@ public class GenericHelp implements CommandHelp { builder.append("GenericHelp ["); - if(summary != null) { + if (summary != null) { builder.append("summary="); builder.append(summary); } - if(description != null) { + if (description != null) { builder.append(", "); builder.append("description="); builder.append(description); diff --git a/base/src/main/java/bjc/utils/cli/objects/BlockReaderCLI.java b/base/src/main/java/bjc/utils/cli/objects/BlockReaderCLI.java index 93d55d8..1c50df3 100644 --- a/base/src/main/java/bjc/utils/cli/objects/BlockReaderCLI.java +++ b/base/src/main/java/bjc/utils/cli/objects/BlockReaderCLI.java @@ -56,7 +56,8 @@ public class BlockReaderCLI { * @param sources * The set of configured I/O sources. */ - public BlockReaderState(Map<String, BlockReader> readers, Map<String, Reader> sources) { + public BlockReaderState(Map<String, BlockReader> readers, + Map<String, Reader> sources) { this.readers = readers; this.sources = sources; } @@ -83,7 +84,7 @@ public class BlockReaderCLI { * Create a new CLI for configuring BlockReaders. * * @param srcs - * The container of initial I/O sources. + * The container of initial I/O sources. */ public BlockReaderCLI(Map<String, Reader> srcs) { stat = new BlockReaderState(srcs); @@ -93,7 +94,7 @@ public class BlockReaderCLI { * Create a new CLI for configuring BlockReaders. * * @param state - * The state object to use. + * The state object to use. */ public BlockReaderCLI(BlockReaderState state) { stat = state; @@ -104,7 +105,7 @@ public class BlockReaderCLI { * Run the command line interface * * @param args - * Ignored CLI args. + * Ignored CLI args. */ public static void main(String[] args) { /* Create/configure I/O sources. */ @@ -122,13 +123,13 @@ public class BlockReaderCLI { * Run the CLI on an input source. * * @param input - * The place to read input from. + * The place to read input from. * * @param srcName - * The name of the place to read input from. + * The name of the place to read input from. * * @param interactive - * Whether or not the source is interactive + * Whether or not the source is interactive */ public void run(Scanner input, String srcName, boolean interactive) { int lno = 0; @@ -146,12 +147,15 @@ public class BlockReaderCLI { /* Parse the command. */ Command com = Command.fromString(ln, lno, srcName); /* Ignore blank commands. */ - if (com == null) continue; + if (com == null) + continue; /* Handle a command. */ CommandStatus sts = handleCommand(com, interactive); /* Exit if we finished or encountered a fatal error. */ - if (sts == FINISH || sts == ERROR) { return; } + if (sts == FINISH || sts == ERROR) { + return; + } } while (input.hasNextLine()); } @@ -159,11 +163,10 @@ public class BlockReaderCLI { * Handle a command. * * @param com - * The command to handle + * The command to handle * * @param interactive - * Whether the current input source is interactive or - * not. + * Whether the current input source is interactive or not. * @return The status of the executed command. */ public CommandStatus handleCommand(Command com, boolean interactive) { @@ -186,7 +189,8 @@ public class BlockReaderCLI { case "exit": case "quit": if (interactive) - System.out.printf("Exiting reader-conf, %d readers configured in %d commands\n", + System.out.printf( + "Exiting reader-conf, %d readers configured in %d commands\n", stat.readers.size(), com.lno); return FINISH; default: @@ -244,18 +248,19 @@ public class BlockReaderCLI { try { Pattern pat = Pattern.compile(filter); - Predicate<Block> pred = (block) -> { + Predicate<Block> pred = block -> { Matcher mat = pat.matcher(block.contents); return mat.matches(); }; - BlockReader reader = new FilteredBlockReader(stat.readers.get(readerName), pred); + BlockReader reader + = new FilteredBlockReader(stat.readers.get(readerName), pred); stat.readers.put(blockName, reader); } catch (PatternSyntaxException psex) { - LOGGER.severe(com.error("Invalid regular expression '%s' for filter. (%s)\n", filter, - psex.getMessage())); + LOGGER.severe(com.error("Invalid regular expression '%s' for filter. (%s)\n", + filter, psex.getMessage())); return FAIL; } @@ -319,7 +324,8 @@ public class BlockReaderCLI { return FAIL; } - BlockReader reader = new ToggledBlockReader(stat.readers.get(parts[1]), stat.readers.get(parts[2])); + BlockReader reader = new ToggledBlockReader(stat.readers.get(parts[1]), + stat.readers.get(parts[2])); stat.readers.put(blockName, reader); return SUCCESS; @@ -355,7 +361,8 @@ public class BlockReaderCLI { return FAIL; } - BlockReader reader = new LayeredBlockReader(stat.readers.get(parts[1]), stat.readers.get(parts[2])); + BlockReader reader = new LayeredBlockReader(stat.readers.get(parts[1]), + stat.readers.get(parts[2])); stat.readers.put(blockName, reader); return SUCCESS; @@ -460,12 +467,14 @@ public class BlockReaderCLI { /* Get the delimiter, and create the reader. */ try { - BlockReader reader = new SimpleBlockReader(delim, stat.sources.get(sourceName)); + BlockReader reader + = new SimpleBlockReader(delim, stat.sources.get(sourceName)); stat.readers.put(blockName, reader); } catch (PatternSyntaxException psex) { - LOGGER.severe(com.error("Invalid regular expression '%s' for delimiter. (%s)\n", delim, - psex.getMessage())); + LOGGER.severe( + com.error("Invalid regular expression '%s' for delimiter. (%s)\n", + delim, psex.getMessage())); return FAIL; } diff --git a/base/src/main/java/bjc/utils/cli/objects/Command.java b/base/src/main/java/bjc/utils/cli/objects/Command.java index 2be7fcd..ce2a985 100644 --- a/base/src/main/java/bjc/utils/cli/objects/Command.java +++ b/base/src/main/java/bjc/utils/cli/objects/Command.java @@ -60,18 +60,19 @@ public class Command { * Create a new command. * * @param ln - * The string to get the command from. + * The string to get the command from. * * @param lno - * The number of the line the command came from. + * The number of the line the command came from. * * @param ioSrc - * The name of where the I/O came from. + * The name of where the I/O came from. */ public Command(String ln, int lno, String ioSrc) { int idx = ln.indexOf(' '); - if (idx == -1) idx = ln.length(); + if (idx == -1) + idx = ln.length(); /* Grab command parts. */ full = ln; @@ -86,15 +87,14 @@ public class Command { /** * Removes up until the first occurrence of a particular string for the * remaining command, and returns the removed string. - * + * * By default, both the substring and the remaining text are trimmed * (leading/trailing spaces removed). - * + * * @param delm - * The delimiter to stop substringing at. - * - * @return The substring, or null if there is no occurrence of the - * delimiter. + * The delimiter to stop substringing at. + * + * @return The substring, or null if there is no occurrence of the delimiter. */ public String trimTo(String delm) { return trimTo(delm, true); @@ -103,19 +103,19 @@ public class Command { /** * Removes up until the first occurrence of a particular string for the * remaining command, and returns the removed string. - * + * * @param delm - * The delimiter to stop substringing at. + * The delimiter to stop substringing at. * @param doTrim - * Whether or not to trim the substring and remaining - * command (Remove leading/trailing spaces). - * - * @return The substring, or null if there is no occurrence of the - * delimiter. + * Whether or not to trim the substring and remaining command + * (Remove leading/trailing spaces). + * + * @return The substring, or null if there is no occurrence of the delimiter. */ public String trimTo(String delm, boolean doTrim) { int idx = remn.indexOf(delm); - if (idx == -1) return null; + if (idx == -1) + return null; String tmp = remn.substring(0, idx); remn = remn.substring(idx); @@ -129,15 +129,15 @@ public class Command { } /** - * Removes up until the first occurrence of a particular regex for the - * remaining command, and returns the removed string. - * + * Removes up until the first occurrence of a particular regex for the remaining + * command, and returns the removed string. + * * By default, both the substring and the remaining text are trimmed * (leading/trailing spaces removed). - * + * * @param rDelm - * The regex to stop substringing at. - * + * The regex to stop substringing at. + * * @return The string, up to the matched pattern. */ public String trimToRX(String rDelm) { @@ -145,15 +145,15 @@ public class Command { } /** - * Removes up until the first occurrence of a particular regex for the - * remaining command, and returns the removed string. - * + * Removes up until the first occurrence of a particular regex for the remaining + * command, and returns the removed string. + * * By default, both the substring and the remaining text are trimmed * (leading/trailing spaces removed). - * + * * @param delm - * The regex to stop substringing at. - * + * The regex to stop substringing at. + * * @return The string, up to the matched pattern. */ public String trimToRX(Pattern delm) { @@ -161,15 +161,15 @@ public class Command { } /** - * Removes up until the first occurrence of a particular regex for the - * remaining command, and returns the removed string. - * + * Removes up until the first occurrence of a particular regex for the remaining + * command, and returns the removed string. + * * @param rDelm - * The regex to stop substringing at. + * The regex to stop substringing at. * @param doTrim - * Whether or not to trim the substring and remaining - * command (Remove leading/trailing spaces). - * + * Whether or not to trim the substring and remaining command + * (Remove leading/trailing spaces). + * * @return The string, up to the matched pattern. */ public String trimToRX(String rDelm, boolean doTrim) { @@ -177,20 +177,21 @@ public class Command { } /** - * Removes up until the first occurrence of a particular regex for the - * remaining command, and returns the removed string. + * Removes up until the first occurrence of a particular regex for the remaining + * command, and returns the removed string. * * @param delm - * The regex to stop substringing at. + * The regex to stop substringing at. * @param doTrim - * Whether or not to trim the substring and remaining - * command (Remove leading/trailing spaces). - * + * Whether or not to trim the substring and remaining command + * (Remove leading/trailing spaces). + * * @return The string, up to the matched pattern. */ public String trimToRX(Pattern delm, boolean doTrim) { Matcher mat = delm.matcher(remn); - if (!mat.find()) return null; + if (!mat.find()) + return null; String tmp = remn.substring(0, mat.start()); remn = remn.substring(mat.end()); @@ -206,15 +207,14 @@ public class Command { /** * Removes up until the first occurrence of a particular string for the * remaining command, and returns the removed string. - * + * * By default, both the substring and the remaining text are trimmed * (leading/trailing spaces removed). - * + * * @param delm - * The delimiter to stop substringing at. - * - * @return The substring, or null if there is no occurrence of the - * delimiter. + * The delimiter to stop substringing at. + * + * @return The substring, or null if there is no occurrence of the delimiter. */ public String trimTo(char delm) { return trimTo(delm, true); @@ -223,19 +223,19 @@ public class Command { /** * Removes up until the first occurrence of a particular string for the * remaining command, and returns the removed string. - * + * * @param delm - * The delimiter to stop substringing at. + * The delimiter to stop substringing at. * @param doTrim - * Whether or not to trim the substring and remaining - * command (Remove leading/trailing spaces). - * - * @return The substring, or null if there is no occurrence of the - * delimiter. + * Whether or not to trim the substring and remaining command + * (Remove leading/trailing spaces). + * + * @return The substring, or null if there is no occurrence of the delimiter. */ public String trimTo(char delm, boolean doTrim) { int idx = remn.indexOf(delm); - if (idx == -1) return null; + if (idx == -1) + return null; String tmp = remn.substring(0, idx); remn = remn.substring(idx); @@ -250,7 +250,7 @@ public class Command { /** * Check if this command has text after its name. - * + * * @return Whether or not this command has text after its name. */ public boolean hasRemaining() { @@ -260,9 +260,8 @@ public class Command { /** * Parse a command from a string. * - * The main thing this does is ignore blank lines, as well as comments - * marked by #'s either at the start of the line or part of the way - * through the line. + * The main thing this does is ignore blank lines, as well as comments marked by + * #'s either at the start of the line or part of the way through the line. * * @param ln * The string to get the command from. @@ -276,8 +275,10 @@ public class Command { */ public static Command fromString(String ln, int lno, String srcName) { /* Ignore blank lines and comments. */ - if (ln.equals("")) return null; - if (ln.startsWith("#")) return null; + if (ln.equals("")) + return null; + if (ln.startsWith("#")) + return null; /* Trim off comments part-way through the line. */ int idxHash = ln.indexOf('#'); @@ -289,14 +290,13 @@ public class Command { } /** - * Give an informational message about something in relation to this - * command. + * Give an informational message about something in relation to this command. * * @param info - * The informational message. + * The informational message. * * @param parms - * The parameters for the informational message. + * The parameters for the informational message. * @return The information message. */ public String info(String info, Object... parms) { @@ -313,7 +313,7 @@ public class Command { * * @param parms * The parameters for the warning message. - * + * * @return The formatted warning. */ public String warn(String warning, Object... parms) { @@ -326,11 +326,11 @@ public class Command { * Give an error about something in relation to this command. * * @param err - * The error message. + * The error message. * * @param parms - * The parameters for the error message. - * + * The parameters for the error message. + * * @return The formatted error */ public String error(String err, Object... parms) { diff --git a/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java b/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java index fc6e04a..d2595d6 100644 --- a/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java +++ b/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java @@ -41,8 +41,9 @@ public class DefineCLI { this(new HashMap<>(), new HashMap<>(), new HashMap<>(), new HashMap<>()); } - public DefineState(Map<String, UnaryOperator<String>> defines, Map<String, String> strings, - Map<String, String> formats, Map<String, Pattern> patterns) { + public DefineState(Map<String, UnaryOperator<String>> defines, + Map<String, String> strings, Map<String, String> formats, + Map<String, Pattern> patterns) { this.defines = defines; this.strings = strings; @@ -63,14 +64,14 @@ public class DefineCLI { /** * Main method - * + * * @param args - * CLI args + * CLI args */ public static void main(String[] args) { DefineCLI defin = new DefineCLI(); - try(Scanner scn = new Scanner(System.in)) { + try (Scanner scn = new Scanner(System.in)) { defin.run(scn, "console", true); } } @@ -79,23 +80,25 @@ public class DefineCLI { * Run the CLI on an input source. * * @param input - * The place to read input from. + * The place to read input from. * @param ioSource - * The name of the place to read input from. + * The name of the place to read input from. * @param interactive - * Whether or not the source is interactive + * Whether or not the source is interactive */ public void run(Scanner input, String ioSource, boolean interactive) { int lno = 0; - while(input.hasNextLine()) { - if(interactive) System.out.printf("define-conf(%d)>", lno); + while (input.hasNextLine()) { + if (interactive) + System.out.printf("define-conf(%d)>", lno); String ln = input.nextLine(); lno += 1; Command com = Command.fromString(ln, lno, ioSource); - if(com == null) continue; + if (com == null) + continue; handleCommand(com, interactive); } @@ -105,15 +108,15 @@ public class DefineCLI { /** * Handle a command - * + * * @param com - * The command to handle + * The command to handle * @param interactive - * Whether or not our I/O stream is interactive + * Whether or not our I/O stream is interactive * @return The status of the executed command. */ public CommandStatus handleCommand(Command com, boolean interactive) { - switch(com.name) { + switch (com.name) { case "def-string": return defString(com); case "def-format": @@ -129,7 +132,7 @@ public class DefineCLI { private CommandStatus defString(Command com) { List<String> arguments = StringUtils.processArguments(com.remn); - if(arguments.size() < 1) { + if (arguments.size() < 1) { LOGGER.severe(com.error( "def-string expects at least one argument: the name of the string to bind")); return FAIL; @@ -138,14 +141,14 @@ public class DefineCLI { String name = arguments.get(0); String strang; - if(arguments.size() < 2) { + if (arguments.size() < 2) { LOGGER.warning(com.warn("Binding empty string to name '%s'\n", name)); strang = ""; } else { strang = arguments.get(1); } - if(stat.strings.containsKey(name)) { + if (stat.strings.containsKey(name)) { LOGGER.warning(com.warn("Shadowing string '%s'\n", name)); } @@ -157,7 +160,7 @@ public class DefineCLI { private CommandStatus defFormat(Command com) { List<String> arguments = StringUtils.processArguments(com.remn); - if(arguments.size() < 1) { + if (arguments.size() < 1) { LOGGER.severe(com.error( "def-format expects at least one argument: the name of the format to bind")); return FAIL; @@ -166,14 +169,14 @@ public class DefineCLI { String name = arguments.get(0); String fmt; - if(arguments.size() < 2) { + if (arguments.size() < 2) { LOGGER.warning(com.warn("Binding empty format to name '%s'\n", name)); fmt = ""; } else { fmt = arguments.get(1); } - if(stat.formats.containsKey(name)) { + if (stat.formats.containsKey(name)) { LOGGER.warning(com.warn("Shadowing format '%s'\n", name)); } @@ -185,20 +188,20 @@ public class DefineCLI { private CommandStatus bindFormat(Command com) { List<String> strings = StringUtils.processArguments(com.remn); - if(strings.size() < 2) { + if (strings.size() < 2) { LOGGER.severe(com.error( "Binding a format requires at least two arguments: the format to bind, and the name to bind it to.")); return FAIL; } String formatName = strings.get(0); - if(!stat.formats.containsKey(formatName)) { + if (!stat.formats.containsKey(formatName)) { LOGGER.severe(com.error("Unknown format %s", formatName)); return FAIL; } String bindName = strings.get(1); - if(stat.strings.containsKey(bindName)) { + if (stat.strings.containsKey(bindName)) { LOGGER.warning(com.warn("Shadowing string '%s'", bindName)); } @@ -209,13 +212,13 @@ public class DefineCLI { itr.next(); itr.next(); - while(itr.hasNext()) { + while (itr.hasNext()) { String name = itr.next(); - if(name.startsWith("$")) { + if (name.startsWith("$")) { String varName = name.substring(1); - if(stat.strings.containsKey(varName)) { + if (stat.strings.containsKey(varName)) { fillIns.add(stat.strings.get(varName)); } else { LOGGER.severe(com.error("Unknown string '%s'", varName)); @@ -226,15 +229,16 @@ public class DefineCLI { } } - // CLFormatter fmt = new CLFormatter(); + // CLFormatter fmt = new CLFormatter(); String formatted = ""; - // try { - // formatted = fmt.formatString(stat.formats.get(formatName), fillIns); - // } catch (IOException ioex) { - // LOGGER.severe(com.error("IOException formatting string: %s", ioex.getMessage())); - // return FAIL; - // } + // try { + // formatted = fmt.formatString(stat.formats.get(formatName), fillIns); + // } catch (IOException ioex) { + // LOGGER.severe(com.error("IOException formatting string: %s", + // ioex.getMessage())); + // return FAIL; + // } stat.strings.put(bindName, formatted); diff --git a/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java b/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java index 27d74c8..59822e4 100644 --- a/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java +++ b/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java @@ -83,8 +83,10 @@ public class DelimSplitterCLI { /* * Handle a input command. */ - private void handleCommand(final String inp, final Scanner scn, final boolean isInteractive) { - if (inp.equals("")) return; + private void handleCommand(final String inp, final Scanner scn, + final boolean isInteractive) { + if (inp.equals("")) + return; int idx = inp.indexOf(' '); @@ -116,14 +118,15 @@ public class DelimSplitterCLI { case "splitter-add": split.addSimpleDelimiters(argArray); if (verbose) { - System.out.println("Added delimiters " + StringUtils.toEnglishList(argArray, true)); + System.out.println( + "Added delimiters " + StringUtils.toEnglishList(argArray, true)); } break; case "splitter-addmulti": split.addMultiDelimiters(argArray); if (verbose) { - System.out.println( - "Added multi-delimiters " + StringUtils.toEnglishList(argArray, true)); + System.out.println("Added multi-delimiters " + + StringUtils.toEnglishList(argArray, true)); } break; case "splitter-addmatch": @@ -150,7 +153,8 @@ public class DelimSplitterCLI { dlm.addGroup(groups.get(arg)); } if (verbose) { - System.out.println("Added groups " + StringUtils.toEnglishList(argArray, true)); + System.out.println( + "Added groups " + StringUtils.toEnglishList(argArray, true)); } break; case "delims-setinitial": @@ -176,7 +180,8 @@ public class DelimSplitterCLI { groups.put(arg, new DelimiterGroup<>(arg)); } if (verbose) { - System.out.println("Created groups " + StringUtils.toEnglishList(argArray, true)); + System.out.println( + "Created groups " + StringUtils.toEnglishList(argArray, true)); } break; case "delimgroups-edit": @@ -238,14 +243,16 @@ public class DelimSplitterCLI { } catch (final FileNotFoundException fnfex) { System.out.println("Couldn't find file '" + args + "'"); } catch (final IOException ioex) { - System.out.println("I/O error with file '" + args + "'\nCause: " + ioex.getMessage()); + System.out.println( + "I/O error with file '" + args + "'\nCause: " + ioex.getMessage()); } } /* * Handle editing a group. */ - private void handleEditGroup(final String arg, final Scanner scn, final boolean isInteractive) { + private void handleEditGroup(final String arg, final Scanner scn, + final boolean isInteractive) { if (!groups.containsKey(arg)) { System.out.println("No group named '" + arg + "'"); return; @@ -306,8 +313,8 @@ public class DelimSplitterCLI { case "add-implied-subgroup": group.implySubgroup(argArray[0], argArray[1]); if (verbose) { - System.out.printf("Made closer '%s' imply a '%s' subgroup\n", argArray[0], - argArray[1]); + System.out.printf("Made closer '%s' imply a '%s' subgroup\n", + argArray[0], argArray[1]); } break; case "add-opener": @@ -320,14 +327,15 @@ public class DelimSplitterCLI { case "add-reopener": group.addPredOpener(new RegexOpener(argArray[0], argArray[1])); if (verbose) { - System.out.printf("Added regex '%s' as opener for '%s'\n", argArray[1], - argArray[0]); + System.out.printf("Added regex '%s' as opener for '%s'\n", + argArray[1], argArray[0]); } break; case "add-recloser": group.addPredCloser(new RegexCloser(argArray[0])); if (verbose) { - System.out.printf("Added parameterized string '%s' as closer\n", argArray[0]); + System.out.printf("Added parameterized string '%s' as closer\n", + argArray[0]); } break; case "debug": @@ -355,8 +363,8 @@ public class DelimSplitterCLI { printDelimSeq(res); } catch (final DelimiterException dex) { - System.out.println("Expression '" + args + "' isn't properly delimited.\n\tCause: " - + dex.getMessage()); + System.out.println("Expression '" + args + + "' isn't properly delimited.\n\tCause: " + dex.getMessage()); } } @@ -392,7 +400,8 @@ public class DelimSplitterCLI { strings = new FunctionalList<>(tks); } try { - final ITree<String> delim = dlm.delimitSequence(strings.toArray(new String[0])); + final ITree<String> delim + = dlm.delimitSequence(strings.toArray(new String[0])); printDelimSeq(delim); } catch (final DelimiterException dex) { @@ -420,7 +429,7 @@ public class DelimSplitterCLI { } private void intPrintDelimTree(final ITree<String> tree, final StringBuilder sb) { - tree.doForChildren((child) -> { + tree.doForChildren(child -> { intPrintDelimNode(child, sb); }); } @@ -462,7 +471,7 @@ public class DelimSplitterCLI { * Main method * * @param args - * Unused CLI args. + * Unused CLI args. */ public static void main(final String[] args) { final DelimSplitterCLI tst = new DelimSplitterCLI(); |
