-
Notifications
You must be signed in to change notification settings - Fork 192
/
Main.java
381 lines (311 loc) · 15.3 KB
/
Main.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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package javarepl;
import com.googlecode.totallylazy.Exceptions;
import com.googlecode.totallylazy.Option;
import com.googlecode.totallylazy.Sequence;
import com.googlecode.totallylazy.Strings;
import com.googlecode.totallylazy.functions.Function1;
import javarepl.client.EvaluationResult;
import javarepl.client.JavaREPLClient;
import javarepl.completion.CompletionCandidate;
import javarepl.completion.CompletionResult;
import jline.Terminal;
import jline.TerminalFactory;
import jline.console.ConsoleReader;
import jline.console.CursorBuffer;
import jline.console.completer.CandidateListCompletionHandler;
import jline.console.completer.CompletionHandler;
import jline.console.history.MemoryHistory;
import org.fusesource.jansi.AnsiConsole;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import static com.googlecode.totallylazy.Exceptions.captureException;
import static com.googlecode.totallylazy.Files.fileOption;
import static com.googlecode.totallylazy.Option.none;
import static com.googlecode.totallylazy.Option.some;
import static com.googlecode.totallylazy.Sequences.empty;
import static com.googlecode.totallylazy.Sequences.sequence;
import static com.googlecode.totallylazy.Strings.replaceAll;
import static com.googlecode.totallylazy.Strings.startsWith;
import static com.googlecode.totallylazy.functions.Callables.compose;
import static com.googlecode.totallylazy.numbers.Numbers.intValue;
import static com.googlecode.totallylazy.numbers.Numbers.valueOf;
import static com.googlecode.totallylazy.predicates.Not.not;
import static java.lang.String.format;
import static java.lang.System.getProperty;
import static java.util.Arrays.asList;
import static javarepl.Utils.applicationVersion;
import static javarepl.Utils.randomServerPort;
import static javarepl.completion.CompletionResult.methods.fromJson;
import static javarepl.completion.CompletionResult.methods.toJson;
import static javax.tools.ToolProvider.getSystemJavaCompiler;
public class Main {
private static Option<Process> process = none();
private static ResultPrinter console;
public static void main(String... args) throws Exception {
console = new ResultPrinter(printColors(args));
Sequence<String> initialExpressions = initialExpressionsFromFile().join(initialExpressionsFromArgs(args));
JavaREPLClient client = clientFor(hostname(args), port(args));
ExpressionReader expressionReader = expressionReaderFor(client, initialExpressions);
Option<String> expression = none();
Option<EvaluationResult> result = none();
while (expression.isEmpty() || !result.isEmpty()) {
expression = expressionReader.readExpression();
if (!expression.isEmpty()) {
result = client.execute(expression.get());
if (!result.isEmpty())
console.printEvaluationResult(result.get());
}
}
}
private static JavaREPLClient clientFor(Option<String> hostname, Option<Integer> port) throws Exception {
console.printInfo(format("Welcome to JavaREPL version %s (%s, Java %s)",
applicationVersion(),
getProperty("java.vm.name"),
getProperty("java.version")));
if (hostname.isEmpty() && port.isEmpty()) {
return startNewLocalInstance("localhost", randomServerPort());
} else {
return connectToRemoteInstance(hostname.getOrElse("localhost"), port.getOrElse(randomServerPort()));
}
}
private static JavaREPLClient connectToRemoteInstance(String hostname, Integer port) {
JavaREPLClient replClient = new JavaREPLClient(hostname, port);
if (!replClient.status().isRunning()) {
console.printError("ERROR: Could not connect to remote REPL instance at http://" + hostname + ":" + port);
System.exit(0);
} else {
console.printInfo("Connected to remote instance at http://" + hostname + ":" + port);
}
String remoteInstanceVersion = replClient.version();
if (!remoteInstanceVersion.equals(applicationVersion())) {
console.printError("WARNING: Client version (" + applicationVersion() + ") is different from remote instance version (" + remoteInstanceVersion + ")");
}
return replClient;
}
private static JavaREPLClient startNewLocalInstance(String hostname, Integer port) throws Exception {
if (getSystemJavaCompiler() == null) {
console.printError("\nERROR: Java compiler not found.\n" +
"This can occur when JavaREPL was run with JRE instead of JDK or JDK is not configured correctly.");
System.exit(0);
}
console.printInfo("Type expression to evaluate, \u001B[32m:help\u001B[0m for more options or press \u001B[32mtab\u001B[0m to auto-complete.");
ProcessBuilder builder = new ProcessBuilder("java", "-cp", System.getProperty("java.class.path"), Repl.class.getCanonicalName(), "--port=" + port);
builder.redirectErrorStream(true);
process = some(builder.start());
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
console.printInfo("\nTerminating...");
process.get().destroy();
}
});
JavaREPLClient replClient = new JavaREPLClient(hostname, port);
if (!waitUntilInstanceStarted(replClient)) {
console.printError("\nERROR: Could not start REPL instance at http://" + hostname + ":" + port);
System.exit(0);
}
return replClient;
}
private static boolean waitUntilInstanceStarted(JavaREPLClient client) throws Exception {
for (int i = 0; i < 500; i++) {
Thread.sleep(10);
if (client.status().isRunning())
return true;
}
return false;
}
private static Sequence<String> initialExpressionsFromArgs(String[] args) {
return sequence(args)
.find(startsWith("--expression="))
.map(replaceAll("--expression=", ""))
.toSequence();
}
private static Sequence<String> initialExpressionsFromFile() {
return fileOption(new File("."), "javarepl.init")
.map(readExpressionsFile())
.getOrElse(empty(String.class));
}
private static Function1<File, Sequence<String>> readExpressionsFile() {
return f -> sequence(Files.readAllLines(f.toPath(), StandardCharsets.UTF_8)).filter(not(Strings::isBlank));
}
private static Option<Integer> port(String[] args) {
return sequence(args).find(startsWith("--port=")).map(compose(replaceAll("--port=", ""), compose(valueOf, intValue)));
}
private static Option<String> hostname(String[] args) {
return sequence(args).find(startsWith("--hostname=")).map(replaceAll("--hostname=", ""));
}
private static Boolean printColors(String[] args) {
return !sequence(args).contains("--noColors");
}
private static ExpressionReader expressionReaderFor(final JavaREPLClient client, Sequence<String> initialExpressions) throws IOException {
return new ExpressionReader(new Function1<Sequence<String>, String>() {
private static final char CTRL_C = (char) 3;
private static final char CTRL_D = (char) 4;
private final ConsoleReader consoleReader;
private Sequence<String> expressions = initialExpressions;
{
consoleReader = new ConsoleReader(System.in, AnsiConsole.out);
consoleReader.setCompletionHandler(new JlineCompletionHandler());
consoleReader.setHistoryEnabled(true);
consoleReader.setExpandEvents(false);
consoleReader.addCompleter(clientCompleter());
consoleReader.addTriggeredAction(CTRL_D, e -> System.exit(0));
}
public String call(Sequence<String> lines) throws Exception {
consoleReader.setPrompt(console.ansiColored(lines.isEmpty() ? "\u001B[1mjava> \u001B[0m" : " \u001B[1m| \u001B[0m"));
consoleReader.setHistory(clientHistory());
return readExpression();
}
private String readExpression() throws IOException {
String expressionLine = null;
if (!expressions.isEmpty()) {
expressionLine = expressions.head();
expressions = expressions.tail();
}
return expressionLine != null ? expressionLine : consoleReader.readLine();
}
private MemoryHistory clientHistory() throws Exception {
MemoryHistory history = new MemoryHistory();
for (String historyItem : client.history()) {
history.add(historyItem);
}
return history;
}
private jline.console.completer.Completer clientCompleter() {
return (expression, cursor, candidates) -> {
try {
CompletionResult result = client.completions(expression);
candidates.addAll(asList(toJson(result)));
return result.candidates().isEmpty() ? -1 : result.position();
} catch (Exception e) {
return -1;
}
};
}
});
}
/**
* Copied from JLine sourcecode and heavily modified
* Original sources: https://raw.github.com/jline/jline2/master/src/main/java/jline/console/completer/CandidateListCompletionHandler.java
*/
public static class JlineCompletionHandler implements CompletionHandler {
// TODO: handle quotes and escaped quotes && enable automatic escaping of whitespace
public boolean complete(final ConsoleReader reader, final List<CharSequence> candidatesJson, final int pos) throws IOException {
CursorBuffer buf = reader.getCursorBuffer();
CompletionResult completionResult = fromJson(sequence(candidatesJson).head().toString());
Sequence<String> candidatesToPrint = empty(String.class);
// if there is only one completion, then fill in the buffer
if (completionResult.candidates().size() == 1) {
CharSequence value = completionResult.candidates().head().value();
// fail if the only candidate is the same as the current buffer
if (value.equals(buf.toString())) {
return false;
}
setBuffer(reader, value, pos);
candidatesToPrint = completionResult.candidates().flatMap(CompletionCandidate::forms);
} else if (completionResult.candidates().size() > 1) {
String value = getUnambiguousCompletions(completionResult.candidates());
setBuffer(reader, value, pos);
candidatesToPrint = completionResult.candidates().map(CompletionCandidate::value);
}
printCandidates(reader, candidatesToPrint.safeCast(CharSequence.class).toList());
// redraw the current console buffer
reader.drawLine();
return true;
}
public static void setBuffer(final ConsoleReader reader, final CharSequence value, final int offset) throws
IOException {
while ((reader.getCursorBuffer().cursor > offset) && reader.backspace()) {
// empty
}
reader.putString(value);
reader.setCursorPosition(offset + value.length());
}
public static void printCandidates(final ConsoleReader reader, Collection<CharSequence> candidates) throws
IOException {
Set<CharSequence> distinct = new HashSet<CharSequence>(candidates);
if (distinct.size() > reader.getAutoprintThreshold()) {
//noinspection StringConcatenation
reader.print(Messages.DISPLAY_CANDIDATES.format(candidates.size()));
reader.flush();
int c;
String noOpt = Messages.DISPLAY_CANDIDATES_NO.format();
String yesOpt = Messages.DISPLAY_CANDIDATES_YES.format();
char[] allowed = {yesOpt.charAt(0), noOpt.charAt(0)};
while ((c = reader.readCharacter(allowed)) != -1) {
String tmp = new String(new char[]{(char) c});
if (noOpt.startsWith(tmp)) {
reader.println();
return;
} else if (yesOpt.startsWith(tmp)) {
break;
} else {
reader.beep();
}
}
}
// copy the values and make them distinct, without otherwise affecting the ordering. Only do it if the sizes differ.
if (distinct.size() != candidates.size()) {
Collection<CharSequence> copy = new ArrayList<CharSequence>();
for (CharSequence next : candidates) {
if (!copy.contains(next)) {
copy.add(next);
}
}
candidates = copy;
}
reader.println();
reader.printColumns(candidates);
}
/**
* Returns a root that matches all the {@link String} elements of the specified {@link List},
* or null if there are no commonalities. For example, if the list contains
* <i>foobar</i>, <i>foobaz</i>, <i>foobuz</i>, the method will return <i>foob</i>.
*/
private String getUnambiguousCompletions(final Sequence<CompletionCandidate> candidates) {
if (candidates == null || candidates.isEmpty()) {
return null;
}
// convert to an array for speed
String[] strings = candidates.map(CompletionCandidate::value).toArray(new String[candidates.size()]);
String first = strings[0];
StringBuilder candidate = new StringBuilder();
for (int i = 0; i < first.length(); i++) {
if (startsWith(first.substring(0, i + 1), strings)) {
candidate.append(first.charAt(i));
} else {
break;
}
}
return candidate.toString();
}
/**
* @return true is all the elements of <i>candidates</i> start with <i>starts</i>
*/
private boolean startsWith(final String starts, final String[] candidates) {
for (String candidate : candidates) {
if (!candidate.startsWith(starts)) {
return false;
}
}
return true;
}
private static enum Messages {
DISPLAY_CANDIDATES,
DISPLAY_CANDIDATES_YES,
DISPLAY_CANDIDATES_NO,;
private static final
ResourceBundle
bundle =
ResourceBundle.getBundle(CandidateListCompletionHandler.class.getName(), Locale.getDefault());
public String format(final Object... args) {
if (bundle == null)
return "";
else
return String.format(bundle.getString(name()), args);
}
}
}
}