-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathSimpleTerminalConsole.java
186 lines (170 loc) · 6.67 KB
/
SimpleTerminalConsole.java
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
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Minecrell <https://github.com/Minecrell>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.minecrell.terminalconsole;
import org.apache.logging.log4j.LogManager;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jline.reader.Completer;
import org.jline.reader.EndOfFileException;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* A simple, optional base implementation of a basic console input command
* reader using {@link TerminalConsoleAppender}. Once started, it displays
* a command prompt ("{@code > }") and reads input commands from the console.
*
* <p><strong>Usage:</strong> Extend this class and implement the abstract
* methods for your application. Consider overriding
* {@link #buildReader(LineReaderBuilder)} to add further features to the
* console (e.g. call {@link LineReaderBuilder#completer(Completer)} with
* a custom completer to provide command completion).</p>
*/
public abstract class SimpleTerminalConsole {
/**
* Determines if the application is still running and accepting input.
*
* @return {@code true} to continue reading input
*/
protected abstract boolean isRunning();
/**
* Run a command entered in the console.
*
* @param command The command line to run
*/
protected abstract void runCommand(String command);
/**
* Shutdown the application and perform a clean exit.
*
* <p>This is called if the application receives SIGINT while reading input,
* e.g. when pressing CTRL+C on most terminal implementations.</p>
*/
protected abstract void shutdown();
/**
* Process an input line entered through the console.
*
* <p>The default implementation trims leading and trailing whitespace
* from the input and skips execution if the command is empty.</p>
*
* @param input The input line
*/
protected void processInput(String input) {
String command = input.trim();
if (!command.isEmpty()) {
runCommand(command);
}
}
/**
* Configures the {@link LineReaderBuilder} and {@link LineReader} with
* additional options.
*
* <p>Override this method to make further changes, (e.g. call
* {@link LineReaderBuilder#appName(String)} or
* {@link LineReaderBuilder#completer(Completer)}).</p>
*
* <p>The default implementation sets some opinionated default options,
* which are considered to be appropriate for most applications:</p>
*
* <ul>
* <li>{@link LineReader.Option#DISABLE_EVENT_EXPANSION}: JLine implements
* <a href="http://www.gnu.org/software/bash/manual/html_node/Event-Designators.html">
* Bash's Event Designators</a> by default. These usually do not
* behave as expected in a simple command environment, so it's
* recommended to disable it.</li>
* <li>{@link LineReader.Option#INSERT_TAB}: By default, JLine inserts
* a tab character when attempting to tab-complete on empty input.
* It is more intuitive to show a list of commands instead.</li>
* </ul>
*
* @param builder The builder to configure
* @return The built line reader
*/
protected LineReader buildReader(LineReaderBuilder builder) {
LineReader reader = builder.build();
reader.setOpt(LineReader.Option.DISABLE_EVENT_EXPANSION);
reader.unsetOpt(LineReader.Option.INSERT_TAB);
return reader;
}
/**
* Start reading commands from the console.
*
* <p>Note that this method won't return until one of the following
* conditions are met:</p>
*
* <ul>
* <li>{@link #isRunning()} returns {@code false}, indicating that the
* application is shutting down.</li>
* <li>{@link #shutdown()} is triggered by the user (e.g. due to
* pressing CTRL+C)</li>
* <li>The input stream is closed.</li>
* </ul>
*/
public void start() {
try {
final @Nullable Terminal terminal = TerminalConsoleAppender.getTerminal();
if (terminal != null) {
readCommands(terminal);
} else {
readCommands(System.in);
}
} catch (IOException e) {
LogManager.getLogger("TerminalConsole").error("Failed to read console input", e);
}
}
private void readCommands(Terminal terminal) {
LineReader reader = buildReader(LineReaderBuilder.builder().terminal(terminal));
TerminalConsoleAppender.setReader(reader);
try {
String line;
while (isRunning()) {
try {
line = reader.readLine("> ");
} catch (EndOfFileException ignored) {
// Continue reading after EOT
continue;
}
if (line == null) {
break;
}
processInput(line);
}
} catch (UserInterruptException e) {
shutdown();
} finally {
TerminalConsoleAppender.setReader(null);
}
}
private void readCommands(InputStream in) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line;
while (isRunning() && (line = reader.readLine()) != null) {
processInput(line);
}
}
}
}