summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/cli/GeneralCommandMode.java
blob: 880e8c56d4a4520d685c7bbf8824e7bc049a384a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package bjc.utils.cli;

import java.util.function.BiConsumer;
import java.util.function.Consumer;

import bjc.utils.funcdata.FunctionalMap;
import bjc.utils.funcdata.IFunctionalMap;

/**
 * A general command mode, with a customizable set of commands
 * 
 * There is a small set of commands which is handled by default. The first
 * is 'list', which lists all the commands the user can input. The second
 * is 'alias', which allows the user to bind a new name to a command
 * 
 * @author ben
 *
 */
public class GeneralCommandMode implements ICommandMode {
	private IFunctionalMap<String, ICommand>		commandHandlers;
	private IFunctionalMap<String, ICommand>		defaultHandlers;

	private IFunctionalMap<String, ICommandHelp>	helpTopics;

	private BiConsumer<String, String[]>			unknownCommandHandler;

	private Consumer<String>						errorOutput;
	private Consumer<String>						normalOutput;

	private String									modeName;

	private String									customPrompt;

	/**
	 * Create a new general command mode
	 * 
	 * @param normalOutput
	 *            The function to use for normal output
	 * @param errorOutput
	 *            The function to use for error output
	 */
	public GeneralCommandMode(Consumer<String> normalOutput,
			Consumer<String> errorOutput) {
		this.normalOutput = normalOutput;
		this.errorOutput = errorOutput;

		commandHandlers = new FunctionalMap<>();
		defaultHandlers = new FunctionalMap<>();

		defaultHandlers.put("list", new GenericCommand((args) -> {
			listCommands();

			return this;
		}, "list\tList available command",
				"Lists all of the commands available in this mode,"
						+ " as well as the commands that are valid in any mode."));

		defaultHandlers.put("alias", new GenericCommand((args) -> {
			aliasCommands(args);

			return this;
		}, "alias\tAlias one command to another",
				"alias gives a command another name it can be invoked by. It is invoked"
						+ " with two arguments, the name of the command to alias"
						+ ", and the alias to give that command."));

		defaultHandlers.put("help", new GenericCommand((args) -> {
			// TODO implement help system
			return this;
		}, "help\tConsult the help system",
				"help consults the internal help system."
						+ " It can be invoked in two ways. Invoking it with no arguments"
						+ " causes it to print out all the topics you can ask for details on,"
						+ " while invoking it with the name of a topic will print the entry"
						+ " for that topic"));
	}

	/**
	 * Add an alias to an existing command
	 * 
	 * @param commandName
	 *            The name of the command to add an alias for
	 * @param aliasName
	 *            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
	 */
	public void addCommandAlias(String commandName, String aliasName) {
		if (commandName == null) {
			throw new NullPointerException(
					"Command name must not be null");
		} else if (aliasName == null) {
			throw new NullPointerException("Alias name must not be null");
		} else if (!commandHandlers.containsKey(commandName)) {
			throw new IllegalArgumentException(
					"Cannot alias non-existant command '" + commandName
							+ "'");
		} else if (commandHandlers.containsKey(aliasName)) {
			throw new IllegalArgumentException("Cannot bind alias '"
					+ aliasName + "' to a command with a bound handler");
		} else {
			commandHandlers.put(aliasName,
					commandHandlers.get(commandName));
		}
	}

	/**
	 * Add a command to this command mode
	 * 
	 * @param command
	 *            The command to add
	 * @param handler
	 *            The handler to use for the specified command
	 * 
	 * @throws IllegalArgumentException
	 *             if the specified command already has a handler
	 *             registered
	 */
	public void addCommandHandler(String command, ICommand handler) {
		if (command == null) {
			throw new NullPointerException("Command must not be null");
		} else if (handler == null) {
			throw new NullPointerException("Handler must not be null");
		} else if (canHandleCommand(command)) {
			throw new IllegalArgumentException("Command " + command
					+ " already has a handler registered");
		} else {
			commandHandlers.put(command, handler);
		}
	}

	private void aliasCommands(String[] args) {
		if (args.length != 2) {
			errorOutput.accept("ERROR: Alias requires two arguments. "
					+ "The command name, and the alias for that command");
		} else {
			String commandName = args[0];
			String aliasName = args[1];

			if (!canHandleCommand(commandName)) {
				errorOutput.accept("ERROR: '" + commandName
						+ "' is not a valid command.");
			} else if (canHandleCommand(aliasName)) {
				errorOutput.accept("ERROR: Cannot overwrite command '"
						+ aliasName + "'");
			} else {
				addCommandAlias(commandName, aliasName);
			}
		}
	}

	@Override
	public boolean canHandleCommand(String command) {
		return commandHandlers.containsKey(command)
				|| defaultHandlers.containsKey(command);
	}

	@Override
	public String getCustomPrompt() {
		if (customPrompt != null) {
			return customPrompt;
		}

		return ICommandMode.super.getCustomPrompt();
	}

	@Override
	public String getName() {
		if (modeName != null) {
			return modeName;
		}

		return ICommandMode.super.getName();
	}

	private void listCommands() {
		normalOutput.accept(
				"The available commands for this mode are as follows:\n");

		commandHandlers.keyList().forEach((commandName) -> {
			normalOutput.accept("\t" + commandName);
		});

		normalOutput.accept(
				"\nThe following commands are available in all modes:\n");

		defaultHandlers.keyList().forEach((commandName) -> {
			normalOutput.accept("\t" + commandName);
		});

		normalOutput.accept("\n");
	}

	@Override
	public ICommandMode processCommand(String command, String[] args) {
		normalOutput.accept("\n");

		if (defaultHandlers.containsKey(command)) {
			return defaultHandlers.get(command).getHandler().handle(args);
		} else if (commandHandlers.containsKey(command)) {
			return commandHandlers.get(command).getHandler().handle(args);
		} else {
			if (args != null) {
				errorOutput.accept("ERROR: Unrecognized command " + command
						+ String.join(" ", args));
			} else {
				errorOutput
						.accept("ERROR: Unrecognized command " + command);
			}

			if (unknownCommandHandler == null) {
				throw new UnsupportedOperationException(
						"Command " + command + " is invalid.");
			}

			unknownCommandHandler.accept(command, args);
		}

		return this;
	}

	/**
	 * Set the custom prompt for this mode
	 * 
	 * @param prompt
	 *            The custom prompt for this mode, or null to disable the
	 *            custom prompt
	 */
	public void setCustomPrompt(String prompt) {
		customPrompt = prompt;
	}

	/**
	 * Set the name of this mode
	 * 
	 * @param name
	 *            The desired name of this mode, or null to use the default
	 *            name
	 */
	public void setModeName(String name) {
		modeName = name;
	}

	/**
	 * Set the handler to use for unknown commands
	 * 
	 * @param handler
	 *            The handler to use for unknown commands
	 */
	public void setUnknownCommandHandler(
			BiConsumer<String, String[]> handler) {
		if (handler == null) {
			throw new NullPointerException("Handler must not be null");
		}

		unknownCommandHandler = handler;
	}

	@Override
	public boolean useCustomPrompt() {
		return customPrompt != null;
	}
}