diff --git a/.forgejo/workflows/java-build.yml b/.forgejo/workflows/java-build.yml new file mode 100644 index 0000000..fc4be96 --- /dev/null +++ b/.forgejo/workflows/java-build.yml @@ -0,0 +1,41 @@ +name: build-java +on: [ push, pull_request ] + +jobs: + build: + runs-on: docker + steps: + - name: checkout repository + uses: https://code.forgejo.org/actions/checkout@v4 + - name: setup jdk + uses: https://github.com/actions/setup-java@v4 + with: + java-version: | + 8 + 21 + distribution: temurin + - name: restore cached dependencies + uses: https://code.forgejo.org/actions/cache/restore@v4 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-Gradle + - name: build + run: ./gradlew build --no-daemon --warning-mode=all + - name: capture build artifacts + uses: https://code.forgejo.org/forgejo/upload-artifact@v4 + with: + name: build-artifacts.zip + path: | + build/libs + !build/libs/*-all.jar + if-no-files-found: error + - name: cache downloaded dependencies + if: ${{ github.ref_name == github.event.repository.default_branch }} + uses: https://code.forgejo.org/actions/cache/save@v4 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-Gradle diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e2fa68a..2c1e08c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,7 +12,7 @@ jobs: matrix: # Use these Java versions java: [ - 17, # Current Java LTS & minimum supported by Minecraft + 21, # Current Java LTS ] # and run on both Linux and Windows os: [ubuntu-22.04, windows-2022] diff --git a/README.md b/README.md index ffac7f9..c7ab260 100644 --- a/README.md +++ b/README.md @@ -38,9 +38,6 @@ Beware that anyone who has write access to the MC server's files is able to edit 5. Restart your Minecraft server and You're good to go! # KNOWN ISSUES -- It is only possible to define a single command at this point - subject to change once I figure out how to do things -- Execution Timeout and Execution block Timeout have no effect on the command at this point. -- The command mode has no effect on the command feedback itself. in any case, the output will be sent in chat +- Execution Timeout and Execution block Timeout have no effect on the command at this point - the console is spamed with debug messages -- threads are not closed after a task exits -- and many more.... +- threads are not closed after a task exit diff --git a/build.gradle b/build.gradle index 6d30805..d17038a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,15 +1,15 @@ plugins { - id 'fabric-loom' version '1.0-SNAPSHOT' + id 'fabric-loom' version '1.10-SNAPSHOT' id 'maven-publish' } -sourceCompatibility = JavaVersion.VERSION_17 -targetCompatibility = JavaVersion.VERSION_17 - -archivesBaseName = project.archives_base_name version = project.mod_version group = project.maven_group +base { + archivesName = project.archives_base_name +} + repositories { // Add repositories to retrieve artifacts from in here. // You should only use this when depending on other mods because @@ -18,6 +18,18 @@ repositories { // for more information about repositories. } +loom { + splitEnvironmentSourceSets() + + mods { + "modid" { + sourceSet sourceSets.main + sourceSet sourceSets.client + } + } + +} + dependencies { // To change the versions see the gradle.properties file minecraft "com.mojang:minecraft:${project.minecraft_version}" @@ -27,23 +39,21 @@ dependencies { // Fabric API. This is technically optional, but you probably want it anyway. modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" - // Uncomment the following line to enable the deprecated Fabric API modules. - // These are included in the Fabric API production distribution and allow you to update your mod to the latest modules at a later more convenient time. - - // modImplementation "net.fabricmc.fabric-api:fabric-api-deprecated:${project.fabric_version}" + compileOnly 'org.projectlombok:lombok:1.18.32' + annotationProcessor 'org.projectlombok:lombok:1.18.32' + } processResources { inputs.property "version", project.version filesMatching("fabric.mod.json") { - expand "version": project.version + expand "version": inputs.properties.version } } tasks.withType(JavaCompile).configureEach { - // Minecraft 1.18 (1.18-pre2) upwards uses Java 17. - it.options.release = 17 + it.options.release = 21 } java { @@ -51,18 +61,24 @@ java { // if it is present. // If you remove this line, sources will not be generated. withSourcesJar() + + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 } jar { + inputs.property "archivesName", project.base.archivesName + from("LICENSE") { - rename { "${it}_${project.archivesBaseName}"} + rename { "${it}_${inputs.properties.archivesName}"} } } // configure the maven publication publishing { publications { - mavenJava(MavenPublication) { + create("mavenJava", MavenPublication) { + artifactId = project.archives_base_name from components.java } } @@ -74,4 +90,4 @@ publishing { // The repositories here will be used for publishing your artifact, not for // retrieving dependencies. } -} +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 1222a90..fe91f33 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,14 +3,15 @@ org.gradle.jvmargs=-Xmx1G org.gradle.parallel=true # Fabric Properties; -minecraft_version=1.20.1 -yarn_mappings=1.20.1+build.10 -loader_version=0.14.22 +minecraft_version=1.21.5 +yarn_mappings=1.21.5+build.1 +loader_version=0.16.14 +loom_version=1.10-SNAPSHOT # Mod Properties -mod_version = 0.0.1+alpha-build03 +mod_version = 1.0.2 maven_group = me.jonasjones archives_base_name = betterconsolemc # Dependencies -fabric_version=0.88.1+1.20.1 +fabric_version=0.126.0+1.21.5 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 943f0cb..a4b76b9 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index f398c33..e18bc25 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 65dcd68..f3b75f3 100755 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -83,10 +85,8 @@ done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -133,10 +133,13 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. @@ -144,7 +147,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac @@ -152,7 +155,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC3045 + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -197,11 +200,15 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ diff --git a/gradlew.bat b/gradlew.bat index 93e3f59..9d21a21 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,6 +13,8 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @@ -43,11 +45,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -57,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail diff --git a/settings.gradle b/settings.gradle index b02216b..75c4d72 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,10 +1,10 @@ pluginManagement { - repositories { - maven { - name = 'Fabric' - url = 'https://maven.fabricmc.net/' - } - mavenCentral() - gradlePluginPortal() - } -} + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + mavenCentral() + gradlePluginPortal() + } +} \ No newline at end of file diff --git a/src/main/java/me/jonasjones/betterconsolemc/BetterConsoleMC.java b/src/main/java/me/jonasjones/betterconsolemc/BetterConsoleMC.java index 97187ed..5d3c85c 100644 --- a/src/main/java/me/jonasjones/betterconsolemc/BetterConsoleMC.java +++ b/src/main/java/me/jonasjones/betterconsolemc/BetterConsoleMC.java @@ -2,17 +2,17 @@ package me.jonasjones.betterconsolemc; import me.jonasjones.betterconsolemc.cmdconfig.CmdConfigHandler; import me.jonasjones.betterconsolemc.cmdconfig.CmdConfigs; -import me.jonasjones.betterconsolemc.command.GameCommandHandler; import me.jonasjones.betterconsolemc.modconfig.ModConfigs; import me.jonasjones.betterconsolemc.util.CommandPreRegistry; import net.fabricmc.api.ModInitializer; -import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.fabricmc.loader.api.FabricLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; +import static me.jonasjones.betterconsolemc.command.GameCommandHandler.registerCommands; + public class BetterConsoleMC implements ModInitializer { // This logger is used to write text to the console and the log file. // It is considered best practice to use your mod id as the logger's name. @@ -24,13 +24,6 @@ public class BetterConsoleMC implements ModInitializer { public static Path CONFIGDIR = FabricLoader.getInstance().getConfigDir(); public static CommandPreRegistry COMMANDPREREGISTRY; - public static void registerCommands() { - for (CommandPreRegistry commandPreRegistry : CmdConfigHandler.FULLREG) { - COMMANDPREREGISTRY = commandPreRegistry; - CommandRegistrationCallback.EVENT.register(GameCommandHandler::register); - } - } - @Override public void onInitialize() { // This code runs as soon as Minecraft is in a mod-load-ready state. @@ -45,7 +38,7 @@ public class BetterConsoleMC implements ModInitializer { } catch (Exception e) { ModConfigs.IS_ENABLED = false; LOGGER.error("SYNTAX ERROR(S) IN COMMAND CONFIG FILE OF BETTERCONSOLEMC"); - LOGGER.error("For security reasons, the mod has therefore beeen disabled and all commands are therefore nonfunctional"); + LOGGER.error("For security reasons, the mod has beeen disabled and all commands are nonfunctional"); } } } diff --git a/src/main/java/me/jonasjones/betterconsolemc/cmdconfig/CmdConfigHandler.java b/src/main/java/me/jonasjones/betterconsolemc/cmdconfig/CmdConfigHandler.java index 15da5a0..95b95cd 100644 --- a/src/main/java/me/jonasjones/betterconsolemc/cmdconfig/CmdConfigHandler.java +++ b/src/main/java/me/jonasjones/betterconsolemc/cmdconfig/CmdConfigHandler.java @@ -20,11 +20,10 @@ public class CmdConfigHandler { public static void getCommands(String path) throws IOException { List commands = new ArrayList(); BufferedReader reader = new BufferedReader(new FileReader(path)); - int linecount = 0; + int linecount = 1; String linecontent = reader.readLine(); - while (linecontent != null) { - if (!linecontent.startsWith("#") || linecontent.equals("")) { - System.out.println(linecontent); + while (!linecontent.isEmpty()) { + if (!linecontent.startsWith("#") || linecontent.equals("\n")) { try { commands.add(preRegisterCommands(linecontent)); } catch (Exception e) { @@ -33,6 +32,9 @@ public class CmdConfigHandler { } } linecontent = reader.readLine(); + if (linecontent == null) { + break; + } linecount++; } FULLREG = commands; @@ -43,12 +45,11 @@ public class CmdConfigHandler { CmdMode commandMode = getCommandMode(configCommandDef); int permissionLevel = getPermissionLevel(configCommandDef); int execTimeout = getExecTimeout(configCommandDef); - int execRerunTimeout = getExecRerunTiemout(configCommandDef); boolean broadcastToOP = doBroadcastToOP(configCommandDef); String ingameCommand = getIngameCommand(configCommandDef); String command = getCommand(configCommandDef); - preRegisteredCommand.init(commandMode, command, permissionLevel, execTimeout, ingameCommand, execRerunTimeout, broadcastToOP); + preRegisteredCommand.init(commandMode, command, permissionLevel, execTimeout, ingameCommand, broadcastToOP); return preRegisteredCommand; } @@ -80,21 +81,17 @@ public class CmdConfigHandler { } private static String getIngameCommand(String configCommandDef) { - return getSplitCommandPartByIndex(configCommandDef, 5); - } - - private static int getExecRerunTiemout(String configCommandDef) { - return Integer.parseInt(getSplitCommandPartByIndex(configCommandDef, 3)); - } - - private static String getBroadcastToOP(String configCommandDef) throws BroadcastToOpNotBoolException { return getSplitCommandPartByIndex(configCommandDef, 4); } + private static String getBroadcastToOP(String configCommandDef) throws BroadcastToOpNotBoolException { + return getSplitCommandPartByIndex(configCommandDef, 3); + } + private static boolean doBroadcastToOP(String configCommandDef) throws BroadcastToOpNotBoolException { - if (getSplitCommandPartByIndex(configCommandDef, 4).equals("true")) { + if (getSplitCommandPartByIndex(configCommandDef, 3).equals("true")) { return true; - } else if (getSplitCommandPartByIndex(configCommandDef, 5).equals("false")) { + } else if (getSplitCommandPartByIndex(configCommandDef, 4).equals("false")) { return false; } else { throw new BroadcastToOpNotBoolException(); @@ -102,7 +99,7 @@ public class CmdConfigHandler { } private static String getCommand(String configCommandDef) throws Exception { - return configCommandDef.replaceFirst(getCommandMode(configCommandDef).name() + " " + getPermissionLevel(configCommandDef) + " " + getExecTimeout(configCommandDef) + " " + getExecRerunTiemout(configCommandDef) + " " + getBroadcastToOP(configCommandDef) + " " + getIngameCommand(configCommandDef) + " ", "") + return configCommandDef.replaceFirst(getCommandMode(configCommandDef).name() + " " + getPermissionLevel(configCommandDef) + " " + getExecTimeout(configCommandDef) + " " + getBroadcastToOP(configCommandDef) + " " + getIngameCommand(configCommandDef) + " ", "") .replaceFirst("\"", "") .replaceAll("\"$", ""); } diff --git a/src/main/java/me/jonasjones/betterconsolemc/cmdconfig/CmdConfigs.java b/src/main/java/me/jonasjones/betterconsolemc/cmdconfig/CmdConfigs.java index ed238c6..3451835 100644 --- a/src/main/java/me/jonasjones/betterconsolemc/cmdconfig/CmdConfigs.java +++ b/src/main/java/me/jonasjones/betterconsolemc/cmdconfig/CmdConfigs.java @@ -22,12 +22,12 @@ public class CmdConfigs { private static void createConfigs() { cmdconfigs.addSingleLineComment("This is the command configuration file for BetterConsoleMC"); if (ISWINDOWS) { - cmdconfigs.addSingleLineComment("This message is there to remind you that the mod is running on a WINODWS machine"); + cmdconfigs.addSingleLineComment("This message is there to remind you that the mod is running on a WINDOWS machine"); } else { cmdconfigs.addSingleLineComment("This message is there to remind you that the mod is running on a UNIX-LIKE machine"); } cmdconfigs.addSingleLineComment("The general syntax of defining a command goes like this:"); - cmdconfigs.addSingleLineComment("[Command Mode] [Permissione Level] [Execution Timeout] [Execution Block Timeout] [Broadcast to OP] [Ingame Command name] [command to execute]"); + cmdconfigs.addSingleLineComment("[Command Mode] [Permission Level] [Execution Timeout] [Broadcast to OP] [In-game Command name] [command to execute]"); cmdconfigs.addSingleLineComment("Documentation and examples are available at the wiki of the repository"); } diff --git a/src/main/java/me/jonasjones/betterconsolemc/command/GameCommandHandler.java b/src/main/java/me/jonasjones/betterconsolemc/command/GameCommandHandler.java index 003372c..b596029 100644 --- a/src/main/java/me/jonasjones/betterconsolemc/command/GameCommandHandler.java +++ b/src/main/java/me/jonasjones/betterconsolemc/command/GameCommandHandler.java @@ -3,8 +3,11 @@ package me.jonasjones.betterconsolemc.command; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.context.CommandContext; import me.jonasjones.betterconsolemc.BetterConsoleMC; +import me.jonasjones.betterconsolemc.cmdconfig.CmdConfigHandler; import me.jonasjones.betterconsolemc.system.ShellCommand; import me.jonasjones.betterconsolemc.util.CommandPreRegistry; +import me.jonasjones.betterconsolemc.util.Constants; +import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.minecraft.command.CommandRegistryAccess; import net.minecraft.server.command.CommandManager; import net.minecraft.server.command.ServerCommandSource; @@ -13,21 +16,31 @@ import net.minecraft.text.Text; import static me.jonasjones.betterconsolemc.BetterConsoleMC.COMMANDPREREGISTRY; public class GameCommandHandler { - public static void register(CommandDispatcher serverCommandSourceCommandDispatcher, CommandRegistryAccess commandRegistryAccess, CommandManager.RegistrationEnvironment registrationEnvironment) { - serverCommandSourceCommandDispatcher.register((CommandManager.literal(COMMANDPREREGISTRY.getIngamecommand()).requires(source -> source.hasPermissionLevel(COMMANDPREREGISTRY.getPermissionLevel())) + public static void registerCommands() { + CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> { + for (CommandPreRegistry commandPreRegistry : CmdConfigHandler.FULLREG) { + COMMANDPREREGISTRY = commandPreRegistry; + register(dispatcher, registryAccess, environment, COMMANDPREREGISTRY); + } + }); + } + + public static void register(CommandDispatcher serverCommandSourceCommandDispatcher, CommandRegistryAccess commandRegistryAccess, CommandManager.RegistrationEnvironment registrationEnvironment, CommandPreRegistry commandPreRegistry) { + + serverCommandSourceCommandDispatcher.register((CommandManager.literal(commandPreRegistry.getIngamecommand()).requires(source -> source.hasPermissionLevel(commandPreRegistry.getPermissionLevel())) .executes((context -> { - context.getSource().sendFeedback(() -> runCommand(COMMANDPREREGISTRY, context), COMMANDPREREGISTRY.doBroadcastToOp()); + if (commandPreRegistry.getCommandmode() == Constants.CmdMode.RETURN) { + runCommand(commandPreRegistry, context); + return 1; + } return 1; }))) ); } public static Text runCommand(CommandPreRegistry commandPreRegistry, CommandContext context) { - new Thread(() -> { - ShellCommand.execute(commandPreRegistry, context); - }).start(); - return Text.of("Return"); + return Text.of(ShellCommand.execute(commandPreRegistry, context)); } public static void returnCommandOutput(String cmd, String commandFeedback, CommandContext context) { diff --git a/src/main/java/me/jonasjones/betterconsolemc/modconfig/ModConfigs.java b/src/main/java/me/jonasjones/betterconsolemc/modconfig/ModConfigs.java index 42c44c4..8120e4b 100644 --- a/src/main/java/me/jonasjones/betterconsolemc/modconfig/ModConfigs.java +++ b/src/main/java/me/jonasjones/betterconsolemc/modconfig/ModConfigs.java @@ -7,6 +7,7 @@ public class ModConfigs { public static SimpleConfig MODCONFIG; public static boolean IS_ENABLED; public static boolean REUQIRE_OP; + public static boolean LOG_CMD_OUTPUT; private static ModConfigProvider modconfigs; public static void registerConfigs() { @@ -22,11 +23,13 @@ public class ModConfigs { modconfigs.addSingleLineComment("This is the config file for BetterConsoleMC"); modconfigs.addKeyValuePair(new Pair<>("bettercmd.enable", true), "whether or not to the mod is enabled or not."); modconfigs.addKeyValuePair(new Pair<>("bettercmd.requireOp", true), "whether or not operator level is required in order to run commands."); + modconfigs.addKeyValuePair(new Pair<>("bettercmd.logCmdOutput", false), "whether or not to log the output of commands to the console."); } private static void assignConfigs() { IS_ENABLED = MODCONFIG.getOrDefault("cmd.enable", true); REUQIRE_OP = MODCONFIG.getOrDefault("cmd.requireOp", true); + LOG_CMD_OUTPUT = MODCONFIG.getOrDefault("cmd.logCmdOutput", false); SimpleConfig.LOGGER.info("All " + modconfigs.getConfigsList().size() + " have been set properly"); } diff --git a/src/main/java/me/jonasjones/betterconsolemc/modconfig/SimpleConfig.java b/src/main/java/me/jonasjones/betterconsolemc/modconfig/SimpleConfig.java index 993e461..d72767b 100644 --- a/src/main/java/me/jonasjones/betterconsolemc/modconfig/SimpleConfig.java +++ b/src/main/java/me/jonasjones/betterconsolemc/modconfig/SimpleConfig.java @@ -62,8 +62,10 @@ public class SimpleConfig { try { loadConfig(); } catch (Exception e) { - LOGGER.error(identifier + " failed to load!"); - LOGGER.trace(e); + if (!identifier.equals("Config 'betterconsolemc-commands_config'")) { // this is good code, I swear + LOGGER.error(identifier + " failed to load!"); + LOGGER.trace(e); + } broken = true; } } diff --git a/src/main/java/me/jonasjones/betterconsolemc/system/ShellCommand.java b/src/main/java/me/jonasjones/betterconsolemc/system/ShellCommand.java index d8896aa..6f30739 100644 --- a/src/main/java/me/jonasjones/betterconsolemc/system/ShellCommand.java +++ b/src/main/java/me/jonasjones/betterconsolemc/system/ShellCommand.java @@ -3,15 +3,19 @@ package me.jonasjones.betterconsolemc.system; import com.mojang.brigadier.context.CommandContext; import me.jonasjones.betterconsolemc.BetterConsoleMC; import me.jonasjones.betterconsolemc.command.GameCommandHandler; +import me.jonasjones.betterconsolemc.modconfig.ModConfigs; import me.jonasjones.betterconsolemc.util.CommandPreRegistry; import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.text.Text; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ShellCommand { - public static int execute(CommandPreRegistry command, CommandContext context) { + public static String execute(CommandPreRegistry command, CommandContext context) { + + StringBuilder output = new StringBuilder(); ProcessBuilder processBuilder = new ProcessBuilder(); if (BetterConsoleMC.ISWINDOWS) { @@ -24,26 +28,60 @@ public class ShellCommand { Process process = processBuilder.start(); + //set timeout + long timeout = System.currentTimeMillis()/1000L + command.getExecTimeout(); + //if timeout is 0, set it to not have a timeout + if (command.getExecTimeout() == 0) { + timeout = Long.MAX_VALUE; + } + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; + // WIP + //System.out.println("TIMEOUT: " + timeout); + //System.out.println("TIME: " + System.currentTimeMillis()/1000L); + + long finalTimeout = timeout; + new Thread(() -> { + while (System.currentTimeMillis()/1000L < finalTimeout) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + if (process.isAlive()) { + process.destroy(); + } + }).start(); + while ((line = reader.readLine()) != null) { - GameCommandHandler.returnCommandOutput(command.getCommand(), line, context); + if (ModConfigs.LOG_CMD_OUTPUT) { + GameCommandHandler.returnCommandOutput(command.getCommand(), line, context); + } + //get the ingame command name + output.append("[").append(command.getIngamecommand()).append("]").append(line).append("\n"); + String finalLine = line; + context.getSource().sendFeedback(() -> Text.of("[" + command.getIngamecommand() + "] " + finalLine), command.isBroadcastToOp()); } - int exitCode = process.waitFor(); - if (exitCode == 0) { - BetterConsoleMC.LOGGER.info("Exited with error code : " + exitCode); - } else { - BetterConsoleMC.LOGGER.error("Exited with error code : " + exitCode); + //quit the process if it's still running + if (process.isAlive()) { + process.destroy(); } + // Read buffered reader line by line and append to output with prefix of command before each line + + int exitCode = process.waitFor(); + BetterConsoleMC.LOGGER.info("Exited with error code : " + exitCode); + } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } - return 1; + return output.toString(); } } diff --git a/src/main/java/me/jonasjones/betterconsolemc/util/CommandPreRegistry.java b/src/main/java/me/jonasjones/betterconsolemc/util/CommandPreRegistry.java index 65fc042..4bbb280 100644 --- a/src/main/java/me/jonasjones/betterconsolemc/util/CommandPreRegistry.java +++ b/src/main/java/me/jonasjones/betterconsolemc/util/CommandPreRegistry.java @@ -1,49 +1,22 @@ package me.jonasjones.betterconsolemc.util; +import lombok.Getter; + +@Getter public class CommandPreRegistry { //TODO: Add timeout before command can be ran again (unixtimestamp) private Constants.CmdMode commandmode; private String command; private int permissionLevel; private int execTimeout; private String ingamecommand; - private int execRerunTimeout; private boolean broadcastToOp; - public void init(Constants.CmdMode commandmode, String command, int permissionLevel, int execTimeout, String ingamecommand, int execRerunTimeout, boolean broadcastToOp) { + public void init(Constants.CmdMode commandmode, String command, int permissionLevel, int execTimeout, String ingamecommand, boolean broadcastToOp) { this.commandmode = commandmode; this.command = command; this.permissionLevel = permissionLevel; this.execTimeout = execTimeout; this.ingamecommand = ingamecommand; - this.execRerunTimeout = execRerunTimeout; this.broadcastToOp = broadcastToOp; } - - public Constants.CmdMode getCommandmode() { - return this.commandmode; - } - - public String getCommand() { - return this.command; - } - - public int getPermissionLevel() { - return this.permissionLevel; - } - - public int getExecTimeout() { - return this.execTimeout; - } - - public String getIngamecommand() { - return this.ingamecommand; - } - - public int getExecRerunTimeout() { - return this.execRerunTimeout; - } - - public boolean doBroadcastToOp() { - return this.broadcastToOp; - } }