PandaLib/pandalib-cli/src/main/java/fr/pandacube/lib/cli/CLI.java

83 lines
1.9 KiB
Java
Raw Normal View History

package fr.pandacube.lib.cli;
import java.io.IOException;
2021-08-23 03:23:16 +02:00
import java.util.logging.Logger;
import fr.pandacube.lib.cli.commands.CLIBrigadierDispatcher;
import fr.pandacube.lib.cli.log.CLILogger;
import jline.console.ConsoleReader;
import org.fusesource.jansi.AnsiConsole;
2023-08-27 13:37:17 +02:00
import fr.pandacube.lib.util.log.Log;
2022-08-11 01:32:37 +02:00
/**
* Class to handle general standard IO operation for a CLI application. It uses Jlines {@link ConsoleReader} for the
2022-12-02 12:45:53 +01:00
* console rendering, a JUL {@link Logger} for logging, and Brigadier to handle commands.
2022-08-11 01:32:37 +02:00
*/
2022-12-02 12:45:53 +01:00
public class CLI extends Thread {
private final ConsoleReader reader;
private final Logger logger;
2022-08-11 01:32:37 +02:00
/**
* Create a new instance of {@link CLI}.
* @throws IOException if an IO error occurs.
*/
public CLI() throws IOException {
2022-12-02 12:45:53 +01:00
super("Console Thread");
setDaemon(true);
AnsiConsole.systemInstall();
reader = new ConsoleReader();
reader.setPrompt(">");
reader.addCompleter(CLIBrigadierDispatcher.instance);
// configure logger's formatter
System.setProperty("net.md_5.bungee.log-date-format", "yyyy-MM-dd HH:mm:ss");
2021-08-23 03:23:16 +02:00
logger = CLILogger.getLogger(this);
}
2022-08-11 01:32:37 +02:00
/**
* Gets the Jline {@link ConsoleReader} of this CLI instance.
* @return the Jline {@link ConsoleReader} of this CLI instance.
*/
public ConsoleReader getConsoleReader() {
return reader;
}
2022-08-11 01:32:37 +02:00
/**
* Gets the {@link Logger} of this CLI instance.
* @return the {@link Logger} of this CLI instance.
*/
2021-08-23 03:23:16 +02:00
public Logger getLogger() {
return logger;
}
2022-08-11 01:32:37 +02:00
/**
* Runs the main loop of the console interface. This method will not return until the input stream is closed.
*/
2022-12-02 12:45:53 +01:00
@Override
public void run() {
int i = 0;
String line;
try {
while((line = reader.readLine()) != null) {
if (line.trim().equals(""))
continue;
String cmdLine = line;
new Thread(() -> CLIBrigadierDispatcher.instance.execute(cmdLine), "CLICmdThread #"+(i++)).start();
}
} catch (IOException e) {
Log.severe(e);
}
}
}