Skip to content

Commit

Permalink
Merge pull request #322 from Score2/master
Browse files Browse the repository at this point in the history
[6.0.11][publish] Added module expansion-application-console.
  • Loading branch information
Bkm016 authored Jun 13, 2023
2 parents a70de28 + 2cd5c4d commit 0a8d277
Show file tree
Hide file tree
Showing 7 changed files with 293 additions and 7 deletions.
10 changes: 10 additions & 0 deletions expansion/expansion-application-console/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
dependencies {
compileOnly(project(":common"))
compileOnly(project(":platform:platform-application"))

implementation("net.minecrell:terminalconsoleappender:1.3.0")
implementation("org.apache.logging.log4j:log4j-api:2.17.2")
implementation("org.apache.logging.log4j:log4j-core:2.17.2")
implementation("org.apache.logging.log4j:log4j-iostreams:2.17.2")
implementation("org.apache.logging.log4j:log4j-slf4j18-impl:2.17.2")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package taboolib.platform

import taboolib.common.platform.Awake
import taboolib.common.platform.Platform
import taboolib.common.platform.PlatformSide
import taboolib.common.platform.ProxyCommandSender
import taboolib.common.platform.command.*
import taboolib.common.platform.command.component.CommandBase
import taboolib.common.platform.service.PlatformCommand
import taboolib.platform.AppConsole.logger

/**
* @author Score2
* @since 2022/06/07 23:43
*/
@Awake
@PlatformSide([Platform.APPLICATION])
class AppCommand : PlatformCommand {

companion object {

val unknownCommandMessage get() = System.getProperty("taboolib.application.command.unknown.message")
?: "§cUnknown command.".apply { System.setProperty("taboolib.application.command.unknown.message", this) }

val commands = mutableSetOf<Command>()

fun register(command: Command) {
commands.add(command)
}

fun unregister(name: String) {
val command = commands.find { it.command.aliases.contains(name) } ?: return
unregister(name)
}

fun unregister(command: Command) {
commands.remove(command)
}

fun runCommand(content: String) {
if (content.isBlank()) {
return
}
val label = if (content.contains(" ")) content.substringBefore(" ") else content
val command = commands.find { it.aliases.contains(label) } ?: return logger.info(unknownCommandMessage)
val args = if (content.contains(" ")) content.substringAfter(" ").split(" ") else listOf()

command.executor.execute(AppConsole, command.command, label, args.toTypedArray())
}

fun suggest(content: String): List<String> {
fun suggestion() = commands.flatMap { it.aliases }

if (content.isBlank()) {
return suggestion()
}
val label = if (content.contains(" ")) content.substringBefore(" ") else content

val command =
commands.find { it.aliases.contains(label) } ?: return suggestion().filter { it.startsWith(label) }

return if (content.contains(" ")) {
command.completer.execute(
AppConsole,
command.command,
label,
content.substringAfter(" ").split(" ").toTypedArray()
) ?: listOf()
} else {
listOf()
}
}
}


data class Command(
val command: CommandStructure,
val executor: CommandExecutor,
val completer: CommandCompleter,
val commandBuilder: CommandBase.() -> Unit
) {

val aliases get() = listOf(command.name, *command.aliases.toTypedArray())

fun register() =
AppCommand.register(this)

fun unregister() =
AppCommand.unregister(this)

}

override fun registerCommand(
command: CommandStructure,
executor: CommandExecutor,
completer: CommandCompleter,
commandBuilder: CommandBase.() -> Unit
) {
register(Command(command, executor, completer, commandBuilder))
}

override fun unknownCommand(sender: ProxyCommandSender, command: String, state: Int) {
sender.sendMessage("§7$command§r§c§o<--[HERE]")
}

override fun unregisterCommand(label: String) {
unregister(commands.find { it.command.aliases.contains(label) } ?: return)
}

override fun unregisterCommands() {
commands.forEach {
unregister(it)
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package taboolib.platform

import net.minecrell.terminalconsole.SimpleTerminalConsole
import org.apache.logging.log4j.Level
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.io.IoBuilder
import org.jline.reader.Candidate
import org.jline.reader.LineReader
import org.jline.reader.LineReaderBuilder
import taboolib.common.LifeCycle
import taboolib.common.TabooLibCommon
import taboolib.common.platform.Awake
import taboolib.common.platform.Platform
import taboolib.common.platform.PlatformSide
import taboolib.common.platform.ProxyCommandSender
import taboolib.common.platform.command.command
import taboolib.common.platform.function.pluginId
import taboolib.common.platform.function.pluginVersion

/**
* @author Score2
* @since 2022/06/08 13:37
*/
@Awake
@PlatformSide([Platform.APPLICATION])
object AppConsole : SimpleTerminalConsole(), ProxyCommandSender {

val logger = LogManager.getLogger(AppConsole::class.java)

override var isOp = true
override val name = "CONSOLE"
override val origin: Any = this

@Awake(LifeCycle.LOAD)
fun load() {
System.setOut(IoBuilder.forLogger(logger).setLevel(Level.INFO).buildPrintStream())
System.setErr(IoBuilder.forLogger(logger).setLevel(Level.WARN).buildPrintStream())

command("about", description = "about this server") {
execute<ProxyCommandSender> { sender, context, argument ->
sender.sendMessage("§r$pluginId v$pluginVersion")
sender.sendMessage("§rThere are console application booting by §cTabooLib")
}
}
command("help", aliases = listOf("?"), description = "suggest commands") {
execute<ProxyCommandSender> { sender, context, argument ->
sender.sendMessage("§rRegisted §a${AppCommand.commands.size} §rcommands, list:")
AppCommand.commands.forEach {
sender.sendMessage("§r✦ §a${it.command.name}§r<${it.command.aliases.joinToString()}> §8- §2${it.command.description}")
}
}
}
command("stop", aliases = listOf("shutdown"), description = "stop the server") {
execute<ProxyCommandSender> { sender, context, argument ->
TabooLibCommon.testCancel()
}
}
}

@Awake(LifeCycle.ENABLE)
fun enable() {
object : Thread("console handler") {
override fun run() {
AppConsole.start()
}
}.run {
isDaemon = true
start()
}
}

override fun isRunning(): Boolean {
return !TabooLibCommon.isStopped()
}

override fun buildReader(builder: LineReaderBuilder): LineReader {
builder
.appName(pluginId)
.completer { reader, line, candidates ->
val buffer = line.line()
AppCommand.suggest(buffer).forEach {
candidates.add(Candidate(it))
}

}
.option(LineReader.Option.COMPLETE_IN_WORD, true);

return super.buildReader(builder)
}

override fun runCommand(command: String) {
AppCommand.runCommand(command)
}

override fun shutdown() {
TabooLibCommon.testCancel()
}

override fun hasPermission(permission: String): Boolean {
return true
}

override fun isOnline(): Boolean {
return true
}

override fun performCommand(command: String): Boolean {
AppCommand.runCommand(command)
return true
}

override fun sendMessage(message: String) {
logger.info(message)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
log4j.skipJansi=true
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" packages="net.minecrell.terminalconsole">
<Appenders>
<TerminalConsole name="TerminalConsole">
<PatternLayout pattern="[%d{HH:mm:ss} %style{%highlight{%level}{FATAL=red dark, ERROR=red, WARN=yellow bright, INFO=cyan bright, DEBUG=green, TRACE=white}}] %minecraftFormatting{%msg}%n"/>
</TerminalConsole>
<RollingRandomAccessFile name="File" fileName="logs/latest.log" filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="[%d{HH:mm:ss.SSS} %t/%level] %minecraftFormatting{%msg}{strip}%n"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<OnStartupTriggeringPolicy/>
</Policies>
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="TerminalConsole"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,18 @@ class AppIO : PlatformIO {
val date: String
get() = DateFormatUtils.format(System.currentTimeMillis(), "HH:mm:ss")

override val pluginId: String
get() = "application"
val isLog4jEnabled by lazy {
try {
Class.forName("org.apache.log4j.Logger")
true
} catch (e: ClassNotFoundException) {
false
}
}

override var pluginId = "application"

override val pluginVersion: String
get() = "application"
override var pluginVersion = "application"

override val isPrimaryThread: Boolean
get() = true
Expand All @@ -38,15 +45,30 @@ class AppIO : PlatformIO {
}

override fun info(vararg message: Any?) {
message.filterNotNull().forEach { println("[${date}][INFO] $it") }
message.filterNotNull().forEach {
if (isLog4jEnabled)
println(it)
else
println("[${date}][INFO] $it")
}
}

override fun severe(vararg message: Any?) {
message.filterNotNull().forEach { println("[${date}][ERROR] $it") }
message.filterNotNull().forEach {
if (isLog4jEnabled)
println(it)
else
println("[${date}][ERROR] $it")
}
}

override fun warning(vararg message: Any?) {
message.filterNotNull().forEach { println("[${date}][WARN] $it") }
message.filterNotNull().forEach {
if (isLog4jEnabled)
println(it)
else
println("[${date}][WARN] $it")
}
}

override fun releaseResourceFile(path: String, replace: Boolean): File {
Expand Down
1 change: 1 addition & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ fun importExtensions() {
include("expansion:expansion-geek-tool")
include("expansion:expansion-lang-tools")
include("expansion:expansion-ioc")
include("expansion:expansion-application-console")
// 从 common-5 中移除
include("expansion:expansion-javascript")
}
Expand Down

0 comments on commit 0a8d277

Please sign in to comment.