commit 8e51f9e7ca0202c46b037da918222a77715c7ae0 Author: TheBrokenRail Date: Sat Aug 22 22:05:06 2020 -0400 Initial Release diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..550b373 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# gradle + +.gradle/ +build/ +out/ +classes/ + +# eclipse + +*.launch + +# idea + +.idea/ +*.iml +*.ipr +*.iws + +# vscode + +.settings/ +.vscode/ +bin/ +.classpath +.project + +# fabric + +run/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..40f7511 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,4 @@ +# Changelog + +**1.0.0** +* Initial Release \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..324a977 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,41 @@ +pipeline { + agent { + docker { + image 'openjdk:11-jdk' + } + } + stages { + stage('Build') { + steps { + sh './gradlew build javadoc' + } + post { + success { + archiveArtifacts artifacts: 'build/libs/*', fingerprint: true + + publishHTML target: [ + allowMissing: false, + alwaysLinkToLastBuild: false, + keepAll: false, + reportDir: 'build/docs/javadoc', + reportFiles: 'index.html', + reportName: 'JavaDoc' + ] + } + } + } + stage('Publish') { + when { + expression { + return sh(returnStdout: true, script: 'git tag --contains').trim().length() > 0 + } + } + steps { + sh './gradlew publish' + withCredentials([string(credentialsId: 'curseforge_key', variable: 'CURSEFORGE_KEY')]) { + sh './gradlew -Pcurseforge.api_key="${CURSEFORGE_KEY}" curseforge' + } + } + } + } +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a3bfb1c --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# FreshCoffee +This ensures you are running a supported version of Java and can install a supported one if you are not. + +FreshCoffee is Minecraft version-independent. + +## Changelog +[View Changelog](CHANGELOG.md) + +## How To Include +Add this to ``build.gradle``: +```gradle +repositories { + maven { url 'https://maven.thebrokenrail.com' } +} +dependencies { + modRuntime 'com.thebrokenrail:freshcoffee:VERSION' + include 'com.thebrokenrail:freshcoffee:VERSION' + // VERSION = "+", for example "1.0.0+1.16.2" +} +``` + +You can set a minimum version of Java by adding this to ``fabric.mod.json``: +```json +{ + "custom": { + "freshcoffee:minimum_java_version": 14 + } +} +``` + +You can set a maximum version of Java by adding this to ``fabric.mod.json``: +```json +{ + "custom": { + "freshcoffee:maximum_java_version": 14 + } +} +``` \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..f07faa8 --- /dev/null +++ b/build.gradle @@ -0,0 +1,71 @@ +plugins { + id "fabric-loom" version "0.5-SNAPSHOT" + id "maven-publish" +} + +compileJava { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 +} + +version = project.mod_version as Object +group = project.maven_group as Object + +dependencies { + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings "net.fabricmc:yarn:${project.minecraft_version}+build.${project.yarn_build}:v2" + modImplementation "net.fabricmc:fabric-loader:${project.fabric_loader_version}" + + implementation "org.apache.commons:commons-compress:${project.commons_compress_version}" + include "org.apache.commons:commons-compress:${project.commons_compress_version}" +} + +publishing { + publications { + //noinspection GroovyAssignabilityCheck + mavenJava(MavenPublication) { + //noinspection GroovyAssignabilityCheck + artifact(remapJar) { + //noinspection GroovyAssignabilityCheck + builtBy remapJar + } + } + } + repositories { + maven { + url "/data/maven" + } + } +} + +processResources { + inputs.property "version", project.version + + from(sourceSets.main.resources.srcDirs) { + include "fabric.mod.json" + expand "version": project.version + } + + from(sourceSets.main.resources.srcDirs) { + exclude "fabric.mod.json" + } +} + +// ensure that the encoding is set to UTF-8, no matter what the system default is +// this fixes some edge cases with special characters not displaying correctly +// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html +tasks.withType(JavaCompile) { + options.encoding = "UTF-8" +} + +// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task +// if it is present. +// If you remove this task, sources will not be generated. +task sourcesJar(type: Jar, dependsOn: classes) { + classifier "sources" + from sourceSets.main.allSource +} + +jar { + from "LICENSE" +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..61afc4c --- /dev/null +++ b/gradle.properties @@ -0,0 +1,17 @@ +# Done to increase the memory available to gradle. +org.gradle.jvmargs = -Xmx1G + +# Fabric Properties + # check these on https://fabricmc.net/use + minecraft_version = 1.16.2 + curseforge_id = 398250 + simple_minecraft_version = 1.16.2 + yarn_build = 6 + fabric_loader_version = 0.9.0+build.204 + +# Mod Properties + mod_version = 1.0.0 + maven_group = com.thebrokenrail + +# Dependencies + commons_compress_version = 1.20 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..490fda8 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..5531ef0 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Aug 21 15:43:13 EDT 2020 +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..2fe81a7 --- /dev/null +++ b/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# 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"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +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. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..62bd9b9 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,103 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +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. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +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. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..9c07850 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,12 @@ +pluginManagement { + repositories { + jcenter() + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } +} + +rootProject.name = 'freshcoffee' diff --git a/src/main/java/com/thebrokenrail/freshcoffee/FreshCoffee.java b/src/main/java/com/thebrokenrail/freshcoffee/FreshCoffee.java new file mode 100644 index 0000000..396bc3d --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/FreshCoffee.java @@ -0,0 +1,68 @@ +package com.thebrokenrail.freshcoffee; + +import com.thebrokenrail.freshcoffee.config.HardcodedConfig; +import com.thebrokenrail.freshcoffee.dialog.Dialog; +import com.thebrokenrail.freshcoffee.download.AdoptOpenJDK; +import com.thebrokenrail.freshcoffee.util.PlatformUtil; +import com.thebrokenrail.freshcoffee.util.ReLaunchUtil; +import com.thebrokenrail.freshcoffee.util.Util; +import com.thebrokenrail.freshcoffee.util.ExtractUtil; +import com.thebrokenrail.freshcoffee.util.limit.LimitUtil; +import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; + +public class FreshCoffee implements PreLaunchEntrypoint { + @Override + public void onPreLaunch() { + if (Util.JAVA_VERSION < LimitUtil.getMinimumJavaVersion().getValue() || Util.JAVA_VERSION > LimitUtil.getMaximumJavaVersion().getValue()) { + if (LimitUtil.getMinimumJavaVersion().getValue() > LimitUtil.getMaximumJavaVersion().getValue()) { + Dialog.getInstance().showErrorDialog(String.format(HardcodedConfig.MINIMUM_HIGHER_THAN_MAXIMUM_MESSAGE, LimitUtil.getMinimumJavaVersion().toString(), LimitUtil.getMaximumJavaVersion().toString())); + System.exit(1); + } + + ReLaunchUtil.reLaunch(); + + // Download Available JDKs + AdoptOpenJDK.JDK jdk = AdoptOpenJDK.get().get(PlatformUtil.getPlatform()); + + if (jdk != null) { + int choice = Dialog.getInstance().showOptionDialog(String.format(HardcodedConfig.OUTDATED_JAVA_WITH_OFFER_MESSAGE, LimitUtil.getMinimumJavaVersion().toString(), Util.humanReadableByteCount(jdk.binary.packageObj.size, false)), HardcodedConfig.EXIT_BUTTON, HardcodedConfig.INSTALL_BUTTON); + + if (choice != 0) { + // Install + URL url = null; + try { + url = new URL(jdk.binary.packageObj.link); + } catch (MalformedURLException e) { + Util.getLogger().error("AdoptOpenJDK API Returned Invalid URL: " + jdk.binary.packageObj.link); + } + + if (url != null) { + File dir = Util.getJavaDir(jdk.version.semver); + + if (dir.exists()) { + Util.getLogger().info("Removing Invalid Java Installation: " + dir.getAbsolutePath()); + Util.deleteDirectory(dir); + } + + ExtractUtil.extract(url, dir); + } + + ReLaunchUtil.reLaunch(); + + System.exit(1); + } else { + // Exit + System.exit(0); + } + } else { + Dialog.getInstance().showErrorDialog(String.format(HardcodedConfig.OUTDATED_JAVA_MESSAGE, LimitUtil.getMinimumJavaVersion().toString())); + + System.exit(0); + } + } + } +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/config/HardcodedConfig.java b/src/main/java/com/thebrokenrail/freshcoffee/config/HardcodedConfig.java new file mode 100644 index 0000000..6e2c7d9 --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/config/HardcodedConfig.java @@ -0,0 +1,23 @@ +package com.thebrokenrail.freshcoffee.config; + +import java.io.File; + +public final class HardcodedConfig { + public static final String MINIMUM_JSON_KEY = "freshcoffee:minimum_java_version"; + public static final String MAXIMUM_JSON_KEY = "freshcoffee:maximum_java_version"; + + public static final String TITLE = "FreshCoffee"; + + public static final String INSTALL_BUTTON = "Install"; + public static final String EXIT_BUTTON = "Exit"; + + public static final File INSTALL_DIR = new File(System.getProperty("user.home"), ".freshcoffee"); + + public static final String LIMIT_TEXT = "version %s required by %s"; + + public static final String JAVA_IMPLEMENTATION = "hotspot"; + + public static final String OUTDATED_JAVA_MESSAGE = "An installed mod requires a newer version of Java (%s)."; + public static final String OUTDATED_JAVA_WITH_OFFER_MESSAGE = OUTDATED_JAVA_MESSAGE + " Would you like to install it?\n%s will be downloaded."; + public static final String MINIMUM_HIGHER_THAN_MAXIMUM_MESSAGE = "The minimum required version of Java (%s) is greater than maximum allowed version of Java (%s)."; +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/dialog/Dialog.java b/src/main/java/com/thebrokenrail/freshcoffee/dialog/Dialog.java new file mode 100644 index 0000000..b359fca --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/dialog/Dialog.java @@ -0,0 +1,24 @@ +package com.thebrokenrail.freshcoffee.dialog; + +import com.thebrokenrail.freshcoffee.dialog.client.ClientDialog; +import com.thebrokenrail.freshcoffee.dialog.server.ServerDialog; +import net.fabricmc.loader.api.FabricLoader; + +public interface Dialog { + static Dialog getInstance() { + switch (FabricLoader.getInstance().getEnvironmentType()) { + case CLIENT: { + return ClientDialog.INSTANCE; + } + case SERVER: { + return ServerDialog.INSTANCE; + } + default: { + throw new UnsupportedOperationException(); + } + } + } + + int showOptionDialog(String message, String noText, String yesText); + void showErrorDialog(String message); +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/dialog/client/ClientDialog.java b/src/main/java/com/thebrokenrail/freshcoffee/dialog/client/ClientDialog.java new file mode 100644 index 0000000..d287bfd --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/dialog/client/ClientDialog.java @@ -0,0 +1,33 @@ +package com.thebrokenrail.freshcoffee.dialog.client; + +import com.thebrokenrail.freshcoffee.config.HardcodedConfig; +import com.thebrokenrail.freshcoffee.dialog.Dialog; +import com.thebrokenrail.freshcoffee.dialog.server.ServerDialog; + +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.SwingConstants; + +public class ClientDialog implements Dialog { + public static final Dialog INSTANCE = new ClientDialog(); + + private ClientDialog() { + } + + private JLabel format(String message) { + JLabel label = new JLabel(String.format("
%s", message.replaceAll("\n", "
"))); + label.setHorizontalAlignment(SwingConstants.CENTER); + return label; + } + + @Override + public int showOptionDialog(String message, String noText, String yesText) { + return JOptionPane.showOptionDialog(null, format(message), HardcodedConfig.TITLE, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[]{noText, yesText}, yesText); + } + + @Override + public void showErrorDialog(String message) { + ServerDialog.INSTANCE.showErrorDialog(message); + JOptionPane.showMessageDialog(null, format(message), HardcodedConfig.TITLE, JOptionPane.ERROR_MESSAGE); + } +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/dialog/server/ServerDialog.java b/src/main/java/com/thebrokenrail/freshcoffee/dialog/server/ServerDialog.java new file mode 100644 index 0000000..54dd3eb --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/dialog/server/ServerDialog.java @@ -0,0 +1,45 @@ +package com.thebrokenrail.freshcoffee.dialog.server; + +import com.thebrokenrail.freshcoffee.dialog.Dialog; +import com.thebrokenrail.freshcoffee.util.Util; + +import java.util.Locale; +import java.util.Scanner; + +public class ServerDialog implements Dialog { + public static final Dialog INSTANCE = new ServerDialog(); + + private ServerDialog() { + } + + @Override + public int showOptionDialog(String message, String noText, String yesText) { + noText = noText.toLowerCase(Locale.ROOT); + yesText = yesText.toLowerCase(Locale.ROOT); + + Util.getLogger().info(message.replaceAll("\n", " ") + String.format(" (%1$s/%2$s) [%2$s]: ", noText, yesText)); + + Scanner scanner = new Scanner(System.in); + + while (true) { + String line = scanner.nextLine().trim().toLowerCase(Locale.ROOT); + + if (line.length() == 0) { + line = yesText; + } + + if (line.equals(noText)) { + return 0; + } else if (line.equals(yesText)) { + return 1; + } else { + Util.getLogger().error("Invalid Choice: " + line); + } + } + } + + @Override + public void showErrorDialog(String message) { + Util.getLogger().error(message); + } +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/download/AdoptOpenJDK.java b/src/main/java/com/thebrokenrail/freshcoffee/download/AdoptOpenJDK.java new file mode 100644 index 0000000..9d61a42 --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/download/AdoptOpenJDK.java @@ -0,0 +1,135 @@ +package com.thebrokenrail.freshcoffee.download; + +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; +import com.google.gson.annotations.SerializedName; +import com.thebrokenrail.freshcoffee.config.HardcodedConfig; +import com.thebrokenrail.freshcoffee.util.limit.LimitUtil; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public final class AdoptOpenJDK { + public static final class JDK { + public Binary binary; + public Version version; + } + + @SuppressWarnings("unused") + public static final class Binary { + private String architecture; + private String heap_size; + private String image_type; + private String os; + @SerializedName("package") + public Package packageObj; + private String project; + + private boolean isValid() { + return heap_size.equals("normal") && image_type.equals("jre") && project.equals("jdk") && (packageObj.link.endsWith(".zip") || packageObj.link.endsWith(".tar.gz")); + } + } + + @SuppressWarnings("unused") + public static final class Package { + public String link; + public int size; + } + + @SuppressWarnings("unused") + public static final class Version { + public String semver; + } + + private static String urlToString(@SuppressWarnings("SameParameterValue") String urlStr) { + try { + StringBuilder stringBuilder = new StringBuilder(); + URL url = new URL(urlStr); + + try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()))) { + String line; + while ((line = in.readLine()) != null) { + stringBuilder.append(line); + stringBuilder.append('\n'); + } + } + + return stringBuilder.toString(); + } catch (IOException e) { + return null; + } + } + + private static class Platform { + private final String os; + private final String architecture; + + private Platform(String os, String architecture) { + this.os = os; + this.architecture = architecture; + } + + private boolean isValid(JDK jdk) { + return jdk.binary.os.equals(os) && jdk.binary.architecture.equals(architecture); + } + + @Override + public String toString() { + return os + '-' + architecture; + } + } + + private static final String[] PLATFORM_TYPES = new String[]{"linux", "win", "macosx"}; + private static final String[] ARCHITECTURE_TYPES = new String[]{"x64", "i686", "aarch64", "arm32"}; + + private static final Platform[] PLATFORMS; + + static { + PLATFORMS = new Platform[PLATFORM_TYPES.length * ARCHITECTURE_TYPES.length]; + int pos = 0; + for (String platformType : PLATFORM_TYPES) { + for (String architectureType : ARCHITECTURE_TYPES) { + PLATFORMS[pos++] = new Platform(platformType, architectureType); + } + } + } + + public static Map get() { + String data = urlToString(String.format("https://api.adoptopenjdk.net/v3/assets/latest/%s/%s", LimitUtil.getMinimumJavaVersion().getValue(), HardcodedConfig.JAVA_IMPLEMENTATION)); + if (data != null) { + JDK[] allJDKs = null; + + try { + Gson gson = new Gson(); + allJDKs = gson.fromJson(data, JDK[].class); + } catch (JsonSyntaxException ignored) { + } + + if (allJDKs != null) { + Map selectedJDKs = new HashMap<>(); + for (JDK jdk : allJDKs) { + if (jdk.binary.isValid()) { + Platform platform = null; + for (Platform option : PLATFORMS) { + if (option.isValid(jdk)) { + platform = option; + break; + } + } + + if (platform != null) { + selectedJDKs.put(platform.toString(), jdk); + } + } + } + return selectedJDKs; + } + } + return Collections.emptyMap(); + } +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/util/ExtractUtil.java b/src/main/java/com/thebrokenrail/freshcoffee/util/ExtractUtil.java new file mode 100644 index 0000000..5e0bb4b --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/util/ExtractUtil.java @@ -0,0 +1,116 @@ +package com.thebrokenrail.freshcoffee.util; + +import org.apache.commons.compress.archivers.ArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class ExtractUtil { + private static String stripFirstComponent(String file) { + String path = new File(file).getPath(); + String[] parts = path.split(File.separator); + List newParts = new ArrayList<>(Arrays.asList(parts).subList(1, parts.length)); + return String.join(File.separator, newParts); + } + + public static void extract(URL url, File dir) { + Util.getLogger().info("Downloading/Extracting: " + url.toString()); + + try (InputStream stream = url.openConnection().getInputStream()) { + if (url.getFile().endsWith(".tar.gz")) { + extractTarGz(stream, dir); + } else { + extractZip(stream, dir); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static void log(File file) { + Util.getLogger().debug("Extracting: " + file.getAbsolutePath()); + } + + private static void extractTarGz(InputStream stream, File dir) throws IOException { + try (TarArchiveInputStream tar = new TarArchiveInputStream(new GzipCompressorInputStream(stream))) { + byte[] buffer = new byte[1024]; + + ArchiveEntry entry = tar.getNextEntry(); + while (entry != null) { + String fileName = entry.getName(); + File newFile = new File(dir, stripFirstComponent(fileName)); + + if (newFile.getParentFile() != null) { + //noinspection ResultOfMethodCallIgnored + newFile.getParentFile().mkdirs(); + } + + log(newFile); + + if (!entry.isDirectory()) { + FileOutputStream output = new FileOutputStream(newFile); + int len; + while ((len = tar.read(buffer)) > 0) { + output.write(buffer, 0, len); + } + output.close(); + + //noinspection ResultOfMethodCallIgnored + newFile.setExecutable(true); + } else { + //noinspection ResultOfMethodCallIgnored + newFile.mkdir(); + } + + entry = tar.getNextEntry(); + } + } + } + + private static void extractZip(InputStream stream, File dir) throws IOException { + try (ZipInputStream zip = new ZipInputStream(stream)) { + byte[] buffer = new byte[1024]; + + ZipEntry entry = zip.getNextEntry(); + while (entry != null) { + String fileName = entry.getName(); + File newFile = new File(dir, stripFirstComponent(fileName)); + + if (newFile.getParentFile() != null) { + //noinspection ResultOfMethodCallIgnored + newFile.getParentFile().mkdirs(); + } + + log(newFile); + + if (!entry.isDirectory()) { + FileOutputStream output = new FileOutputStream(newFile); + int len; + while ((len = zip.read(buffer)) > 0) { + output.write(buffer, 0, len); + } + output.close(); + + //noinspection ResultOfMethodCallIgnored + newFile.setExecutable(true); + } else { + //noinspection ResultOfMethodCallIgnored + newFile.mkdir(); + } + + entry = zip.getNextEntry(); + } + } + } +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/util/JavaVersionUtil.java b/src/main/java/com/thebrokenrail/freshcoffee/util/JavaVersionUtil.java new file mode 100644 index 0000000..0c4e66c --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/util/JavaVersionUtil.java @@ -0,0 +1,52 @@ +package com.thebrokenrail.freshcoffee.util; + +import com.thebrokenrail.freshcoffee.util.limit.LimitUtil; + +public final class JavaVersionUtil { + private static boolean isNewer(int[] one, int[] two) { + int length = Math.min(one.length, two.length); + for (int i = 0; i < length; i++) { + if (one[i] > two[i]) { + return true; + } + } + return false; + } + + private static int[] toIntArray(String versionStr) { + String[] versionArr = versionStr.split("[.+]"); + + boolean invalid = false; + int[] version = new int[versionArr.length]; + for (int i = 0; i < versionArr.length; i++) { + try { + version[i] = Integer.parseInt(versionArr[i]); + } catch (NumberFormatException e) { + invalid = true; + break; + } + } + + return invalid ? null : version; + } + + public static String getNewest(String[] list) { + String newest = null; + for (String jdk : list) { + int[] version = toIntArray(jdk); + + if (version != null) { + boolean newer = true; + if (version[0] < LimitUtil.getMinimumJavaVersion().getValue() || version[0] > LimitUtil.getMaximumJavaVersion().getValue() || (newest != null && !isNewer(toIntArray(newest), version))) { + newer = false; + } + + if (newer) { + newest = jdk; + } + } + } + + return newest; + } +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/util/PlatformUtil.java b/src/main/java/com/thebrokenrail/freshcoffee/util/PlatformUtil.java new file mode 100644 index 0000000..14e2f32 --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/util/PlatformUtil.java @@ -0,0 +1,56 @@ +package com.thebrokenrail.freshcoffee.util; + +import java.util.Locale; + +public final class PlatformUtil { + private static String getPlatformType() { + String raw = System.getProperty("os.name").toLowerCase(Locale.ROOT); + if (raw.contains("mac")) { + return "macosx"; + } else if (raw.contains("linux")) { + return "linux"; + } else if (raw.contains("windows")) { + return "win"; + } else { + return "other"; + } + } + + private static String getArchitectureType() { + String raw = System.getProperty("os.arch"); + switch (raw) { + case "x86": + case "i386": + case "i686": { + return "i686"; + } + case "amd64": { + return "x64"; + } + case "arm": { + return "arm32"; + } + case "aarch64_be": + case "armv8b": + case "armv8l": + case "aarch64": { + return "aarch64"; + } + default: { + return "other"; + } + } + } + + public static String getPlatform() { + return getPlatformType() + '-' + getArchitectureType(); + } + + static String getExecutableExtension() { + if ("win".equals(getPlatformType())) { + return ".exe"; + } else { + return ""; + } + } +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/util/ReLaunchUtil.java b/src/main/java/com/thebrokenrail/freshcoffee/util/ReLaunchUtil.java new file mode 100644 index 0000000..a4a0d77 --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/util/ReLaunchUtil.java @@ -0,0 +1,134 @@ +package com.thebrokenrail.freshcoffee.util; + +import com.thebrokenrail.freshcoffee.config.HardcodedConfig; +import net.fabricmc.loader.FabricLoader; +import net.fabricmc.loader.game.MinecraftGameProvider; +import net.fabricmc.loader.util.Arguments; +import org.apache.logging.log4j.LogManager; + +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.lang.management.ManagementFactory; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public final class ReLaunchUtil { + private static boolean contains(File dir, File targetFile) { + File[] files = dir.listFiles(); + if (files != null) { + for (File file : files) { + try { + if (file.toPath().toRealPath().equals(targetFile.toPath().toRealPath()) || contains(file, targetFile)) { + return true; + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + } + return false; + } + + private static List getMainArgs() { + boolean isMultiMC; + try { + Class.forName("org.multimc.EntryPoint"); + isMultiMC = true; + } catch (ClassNotFoundException e) { + isMultiMC = false; + } + + if (isMultiMC) { + // Replace MultiMC's Entry-Point With Fabric's + List mainArgs = new ArrayList<>(); + // Set Entry-Point + mainArgs.add(Util.getMainClass()); + // Get Parameters + String[] launchArgs; + try { + Field launchArgsField = MinecraftGameProvider.class.getDeclaredField("arguments"); + launchArgsField.setAccessible(true); + //noinspection deprecation + launchArgs = ((Arguments) launchArgsField.get(FabricLoader.INSTANCE.getGameProvider())).toArray(); + } catch (IllegalAccessException | NoSuchFieldException e) { + throw new RuntimeException(e); + } + // Add Parameters + mainArgs.addAll(Arrays.asList(launchArgs)); + return mainArgs; + } else { + return Arrays.asList(System.getProperty("sun.java.command").split(" ")); + } + } + + private static void reLaunch(String javaBinary) { + List vmArgs = new ArrayList<>(ManagementFactory.getRuntimeMXBean().getInputArguments()); + // Remove Debugger + vmArgs.removeIf(arg -> arg.startsWith("-agentlib") || arg.startsWith("-javaagent")); + + List mainArgs = getMainArgs(); + + String classpathStr = System.getProperty("java.class.path"); + // Remove Built-In Java Libraries From Classpath + List classpath = new ArrayList<>(Arrays.asList(classpathStr.split(File.pathSeparator))); + classpath.removeIf(arg -> { + File file = new File(arg); + File javaHome = new File(System.getProperty("java.home")); + return contains(javaHome, file); + }); + String newClasspathStr = String.join(File.pathSeparator, classpath); + + List args = new ArrayList<>(); + args.add(javaBinary); + args.addAll(vmArgs); + args.add("-cp"); + args.add(newClasspathStr); + args.addAll(mainArgs); + + Util.getLogger().info("ReLaunching Minecraft..."); + + Util.getLogger().debug("Launching: " + String.join(" ", args)); + + // Release Lock On Log File + LogManager.shutdown(); + + Process process; + try { + process = new ProcessBuilder(args).inheritIO().start(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + + try { + int status = process.waitFor(); + System.exit(status); + } catch (InterruptedException e) { + process.destroy(); + } + } + + public static void reLaunch() { + File[] files = HardcodedConfig.INSTALL_DIR.listFiles(); + if (files != null) { + List list = new ArrayList<>(); + for (File file : files) { + if (file.isDirectory()) { + list.add(file.getName()); + } + } + + String newestVersion = JavaVersionUtil.getNewest(list.toArray(new String[0])); + + if (newestVersion != null) { + File javaBinary = new File(new File(Util.getJavaDir(newestVersion), "bin"), "java" + PlatformUtil.getExecutableExtension()); + if (javaBinary.exists() && javaBinary.canExecute()) { + Util.getLogger().info("Using Java Executable: " + javaBinary.getAbsolutePath()); + reLaunch(javaBinary.getAbsolutePath()); + } + } + } + } +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/util/Util.java b/src/main/java/com/thebrokenrail/freshcoffee/util/Util.java new file mode 100644 index 0000000..fd00556 --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/util/Util.java @@ -0,0 +1,69 @@ +package com.thebrokenrail.freshcoffee.util; + +import com.thebrokenrail.freshcoffee.config.HardcodedConfig; +import net.fabricmc.loader.api.FabricLoader; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.File; + +public final class Util { + public static final int JAVA_VERSION; + + static { + String version = System.getProperty("java.version"); + if (version.startsWith("1.")) { + version = version.substring(2, 3); + } else { + int dot = version.indexOf('.'); + if (dot != -1) { + version = version.substring(0, dot); + } + } + JAVA_VERSION = Integer.parseInt(version); + } + + public static File getJavaDir(String version) { + return new File(HardcodedConfig.INSTALL_DIR, version); + } + + public static void deleteDirectory(File directoryToBeDeleted) { + File[] allContents = directoryToBeDeleted.listFiles(); + if (allContents != null) { + for (File file : allContents) { + deleteDirectory(file); + } + } + getLogger().debug("Deleting: " + directoryToBeDeleted.getAbsolutePath()); + //noinspection ResultOfMethodCallIgnored + directoryToBeDeleted.delete(); + } + + public static Logger getLogger() { + return LogManager.getLogger(HardcodedConfig.TITLE); + } + + static String getMainClass() { + switch (FabricLoader.getInstance().getEnvironmentType()) { + case CLIENT: { + return "net.fabricmc.loader.launch.knot.KnotClient"; + } + case SERVER: { + return "net.fabricmc.loader.launch.knot.KnotServer"; + } + default: { + throw new UnsupportedOperationException(); + } + } + } + + public static String humanReadableByteCount(long bytes, boolean si) { + int unit = si ? 1000 : 1024; + if (bytes < unit) { + return bytes + " B"; + } + int exp = (int) (Math.log(bytes) / Math.log(unit)); + String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); + return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); + } +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/util/limit/Limit.java b/src/main/java/com/thebrokenrail/freshcoffee/util/limit/Limit.java new file mode 100644 index 0000000..b3f1da0 --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/util/limit/Limit.java @@ -0,0 +1,73 @@ +package com.thebrokenrail.freshcoffee.util.limit; + +import com.thebrokenrail.freshcoffee.config.HardcodedConfig; +import com.thebrokenrail.freshcoffee.util.Util; +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.fabricmc.loader.api.metadata.ModMetadata; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Limit { + private final boolean isMinimum; + private int value; + private List source = singleton("default"); + + private static String modToString(ModMetadata metadata) { + return metadata.getName() + " (" + metadata.getId() + ')'; + } + + private static List singleton(String value) { + return new ArrayList<>(Collections.singleton(value)); + } + + Limit(boolean isMinimum) { + this.isMinimum = isMinimum; + value = isMinimum ? 0 : Integer.MAX_VALUE; + + String key = isMinimum ? HardcodedConfig.MINIMUM_JSON_KEY : HardcodedConfig.MAXIMUM_JSON_KEY; + + for (ModContainer mod : FabricLoader.getInstance().getAllMods()) { + ModMetadata metadata = mod.getMetadata(); + if (metadata.containsCustomValue(key)) { + try { + int newValue = metadata.getCustomValue(key).getAsNumber().intValue(); + update(newValue, modToString(metadata)); + } catch (ClassCastException e) { + Util.getLogger().error("Invalid " + (isMinimum ? "Minimum" : "Maximum") + " Java Version Specified: " + metadata.getId()); + } + } + } + } + + private void update(int value, String source) { + if (isMinimum ? value > this.value : value < this.value) { + this.value = value; + this.source = singleton(source); + } else if (value == this.value) { + this.source.add(source); + } + } + + public int getValue() { + return value; + } + + @Override + public String toString() { + StringBuilder sourceBuilder = new StringBuilder(); + for (int i = 0; i < source.size(); i++) { + if (i != 0) { + sourceBuilder.append(i == 1 && source.size() - 1 == 1 ? ' ' : ", "); + if (i == source.size() - 1) { + sourceBuilder.append("and "); + } + } + sourceBuilder.append(source.get(i)); + } + + return String.format(HardcodedConfig.LIMIT_TEXT, value, sourceBuilder.toString()); + } +} diff --git a/src/main/java/com/thebrokenrail/freshcoffee/util/limit/LimitUtil.java b/src/main/java/com/thebrokenrail/freshcoffee/util/limit/LimitUtil.java new file mode 100644 index 0000000..d20b8b7 --- /dev/null +++ b/src/main/java/com/thebrokenrail/freshcoffee/util/limit/LimitUtil.java @@ -0,0 +1,23 @@ +package com.thebrokenrail.freshcoffee.util.limit; + +public class LimitUtil { + private static Limit minimumJavaVersion = null; + private static Limit maximumJavaVersion = null; + + private static void update() { + if (minimumJavaVersion == null || maximumJavaVersion == null) { + minimumJavaVersion = new Limit(true); + maximumJavaVersion = new Limit(false); + } + } + + public static Limit getMinimumJavaVersion() { + update(); + return minimumJavaVersion; + } + + public static Limit getMaximumJavaVersion() { + update(); + return maximumJavaVersion; + } +} diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json new file mode 100644 index 0000000..7e2937a --- /dev/null +++ b/src/main/resources/fabric.mod.json @@ -0,0 +1,25 @@ +{ + "schemaVersion": 1, + "id": "freshcoffee", + "version": "${version}", + "name": "FreshCoffee", + "description": "This ensures you are running a supported version of Java and can install a supported one if you are not.", + "authors": [ + "TheBrokenRail" + ], + "contact": { + "homepage": "https://thebrokenrail.com/", + "sources": "https://gitea.thebrokenrail.com/TheBrokenRail/FreshCoffee.git", + "issues": "https://gitea.thebrokenrail.com/TheBrokenRail/FreshCoffee/issues" + }, + "license": "MIT", + "environment": "*", + "entrypoints": { + "preLaunch": [ + "com.thebrokenrail.freshcoffee.FreshCoffee" + ] + }, + "custom": { + "freshcoffee:minimum_java_version": 8 + } +} \ No newline at end of file