diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml new file mode 100644 index 0000000..3900816 --- /dev/null +++ b/.github/workflows/gradle.yml @@ -0,0 +1,21 @@ +name: Java CI + +on: + [push] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Upload to Bintray & CurseForge + run: ./gradlew clean bintrayUpload curseforge + env: + BINTRAY_USER: shedaniel + BINTRAY_KEY: ${{ secrets.BINTRAY_KEY }} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..979dbe0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# Compiled nonsense that does not belong in *source* control +/build +/bin +/.gradle +/out +/classes +/old + +# IDE nonsense that could go in source control but really shouldn't +.classpath +.project +.metadata +.settings +*.launch +*.iml +.idea +*.ipr +*.iws + +# Sekrit files +private.properties + +# Files from bad operating systems :^) +Thumbs.db +.DS_Store \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..cbc5ba6 --- /dev/null +++ b/build.gradle @@ -0,0 +1,80 @@ +plugins { + id "org.jetbrains.kotlin.jvm" version "1.3.72" + id "com.jfrog.bintray" version "1.8.5" + id "java" + id "idea" + id "eclipse" + id "maven" + id "maven-publish" +} + +group "me.shedaniel" +version = "1.0." + (System.getenv("GITHUB_RUN_NUMBER") == null ? "9999" : System.getenv("GITHUB_RUN_NUMBER")) + +sourceCompatibility = targetCompatibility = 1.8 + +repositories { + jcenter() + maven { url "https://maven.fabricmc.net/" } +} + +apply plugin: 'java-gradle-plugin' + +dependencies { + implementation gradleApi() + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.72" + implementation "org.jetbrains.kotlin:kotlin-reflect:1.3.72" + implementation "net.fabricmc:fabric-loom:0.5-SNAPSHOT" + runtime "net.fabricmc:fabric-loom:0.5-SNAPSHOT" + implementation "net.fabricmc:tiny-remapper:0.3.0.70" + implementation "net.fabricmc:tiny-mappings-parser:0.2.2.14" + implementation "org.ow2.asm:asm:8.0" + implementation "org.ow2.asm:asm-commons:8.0" + implementation "org.ow2.asm:asm-tree:8.0" + implementation "org.ow2.asm:asm-util:8.0" +} + +compileKotlin { + kotlinOptions { + jvmTarget = "1.8" + } +} + +gradlePlugin { + plugins { + architect { + id = 'me.shedaniel.architect.plugin' + implementationClass = 'me.shedaniel.architect.plugin.ArchitectPlugin' + } + } +} + +bintray { + user = project.hasProperty('bintrayUser') ? project.property('bintrayUser') : System.getenv('BINTRAY_USER') + key = project.hasProperty('bintrayApiKey') ? project.property('bintrayApiKey') : System.getenv('BINTRAY_KEY') + publications = ["MyPublication"] + publish = true + pkg { + repo = "cloth" + name = "architect-plugin" + userOrg = "shedaniel" + licenses = ["MIT"] + version { + name = project.version + vcsTag = project.version + released = new Date() + vcsUrl = 'https://github.com/shedaniel/architect-plugin.git' + } + } +} + +publishing { + publications { + MyPublication(MavenPublication) { + from components.java + } + } + + repositories { + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..29e08e8 --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official \ 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..62d4c05 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..4b7e1f3 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..fbd7c51 --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/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..5093609 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,104 @@ +@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..67ef925 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'architect-plugin' + diff --git a/src/main/kotlin/me/shedaniel/architect/plugin/ArchitectPlugin.kt b/src/main/kotlin/me/shedaniel/architect/plugin/ArchitectPlugin.kt new file mode 100644 index 0000000..c39aec4 --- /dev/null +++ b/src/main/kotlin/me/shedaniel/architect/plugin/ArchitectPlugin.kt @@ -0,0 +1,29 @@ +package me.shedaniel.architect.plugin + +import org.gradle.api.JavaVersion +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.plugins.JavaPluginExtension + +class ArchitectPlugin : Plugin { + override fun apply(project: Project) { + project.apply(mapOf( + "plugin" to "java", + "plugin" to "eclipse", + "plugin" to "idea" + )) + project.extensions.create("architect", ArchitectPluginExtension::class.java, project) + + project.afterEvaluate { + project.extensions.getByType(JavaPluginExtension::class.java).apply { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + } + + project.tasks.register("remapMcp", RemapMCPTask::class.java) + project.tasks.register("remapMcpFakeMod", RemapMCPTask::class.java) { + it.fakeMod = true + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/shedaniel/architect/plugin/ArchitectPluginExtension.kt b/src/main/kotlin/me/shedaniel/architect/plugin/ArchitectPluginExtension.kt new file mode 100644 index 0000000..02f5512 --- /dev/null +++ b/src/main/kotlin/me/shedaniel/architect/plugin/ArchitectPluginExtension.kt @@ -0,0 +1,45 @@ +package me.shedaniel.architect.plugin + +import org.gradle.api.Project + +open class ArchitectPluginExtension(val project: Project) { + var minecraft = "" + + fun common() { + project.configurations.create("mcp") + project.configurations.create("mcpGenerateMod") + + project.tasks.getByName("remapMcp") { + it as RemapMCPTask + + it.input.set(project.file("${project.buildDir}/libs/${project.properties["archivesBaseName"]}-${project.version}-dev.jar")) + it.archiveClassifier.set("mcp") + it.dependsOn(project.tasks.getByName("jar")) + project.tasks.getByName("build").dependsOn(it) + it.outputs.upToDateWhen { false } + } + + project.tasks.getByName("remapMcpFakeMod") { + it as RemapMCPTask + + it.input.set(project.file("${project.buildDir}/libs/${project.properties["archivesBaseName"]}-${project.version}-dev.jar")) + it.archiveClassifier.set("mcpGenerateMod") + it.dependsOn(project.tasks.getByName("jar")) + project.tasks.getByName("build").dependsOn(it) + it.outputs.upToDateWhen { false } + } + + project.artifacts { + it.add("mcp", mapOf( + "file" to project.file("${project.buildDir}/libs/${project.properties["archivesBaseName"]}-${project.version}-mcp.jar"), + "type" to "jar", + "builtBy" to project.tasks.getByName("remapMcp") + )) + it.add("mcpGenerateMod", mapOf( + "file" to project.file("${project.buildDir}/libs/${project.properties["archivesBaseName"]}-${project.version}-mcpGenerateMod.jar"), + "type" to "jar", + "builtBy" to project.tasks.getByName("remapMcpFakeMod") + )) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/shedaniel/architect/plugin/RemapMCPTask.kt b/src/main/kotlin/me/shedaniel/architect/plugin/RemapMCPTask.kt new file mode 100644 index 0000000..521da90 --- /dev/null +++ b/src/main/kotlin/me/shedaniel/architect/plugin/RemapMCPTask.kt @@ -0,0 +1,194 @@ +@file:Suppress("UnstableApiUsage") + +package me.shedaniel.architect.plugin + +import net.fabricmc.loom.LoomGradleExtension +import net.fabricmc.loom.util.GradleSupport +import net.fabricmc.loom.util.TinyRemapperMappingsHelper +import net.fabricmc.mapping.tree.TinyTree +import net.fabricmc.tinyremapper.IMappingProvider +import net.fabricmc.tinyremapper.NonClassCopyMode +import net.fabricmc.tinyremapper.OutputConsumerPath +import net.fabricmc.tinyremapper.TinyRemapper +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.tasks.TaskAction +import org.gradle.jvm.tasks.Jar +import org.objectweb.asm.ClassWriter +import org.objectweb.asm.Opcodes +import java.io.File +import java.io.FileNotFoundException +import java.io.InputStream +import java.net.URL +import java.nio.file.Files +import java.nio.file.Path +import java.util.* +import kotlin.collections.LinkedHashSet + + +open class RemapMCPTask : Jar() { + private val fromM: String = "named" + private val toM: String = "official" + var fakeMod = false + val input: RegularFileProperty = GradleSupport.getfileProperty(project) + + @TaskAction + fun doTask() { + val input: Path = this.input.asFile.get().toPath() + val output: Path = this.archiveFile.get().asFile.toPath() + + output.toFile().delete() + + if (!Files.exists(input)) { + throw FileNotFoundException(input.toString()) + } + + val remapperBuilder: TinyRemapper.Builder = TinyRemapper.newRemapper() + + val classpathFiles: Set = LinkedHashSet( + project.configurations.getByName("compileClasspath").files + ) + val classpath = classpathFiles.asSequence().map { obj: File -> obj.toPath() }.filter { p: Path -> input != p && Files.exists(p) }.toList().toTypedArray() + + val mappings = getMappings() + val mojmapToMcpClass = createMojmapToMcpClass(mappings) + remapperBuilder.withMappings(remapToMcp(TinyRemapperMappingsHelper.create(mappings, fromM, fromM, false), mojmapToMcpClass)) + remapperBuilder.ignoreFieldDesc(true) + remapperBuilder.skipLocalVariableMapping(true) + + project.logger.lifecycle(":remapping " + input.fileName) + + val architectFolder = project.rootProject.buildDir.resolve("tmp/architect") + architectFolder.deleteRecursively() + architectFolder.mkdirs() + val fakeModId = "generated_" + UUID.randomUUID().toString().filterNot { it == '-' }.take(7) + if (fakeMod) { + val modsToml = architectFolder.resolve("META-INF/mods.toml") + modsToml.parentFile.mkdirs() + modsToml.writeText(""" +modLoader = "javafml" +loaderVersion = "[33,)" +license = "Generated" +[[mods]] +modId = "$fakeModId" + """.trimIndent()) + val mcmeta = architectFolder.resolve("pack.mcmeta") + mcmeta.parentFile.mkdirs() + mcmeta.writeText(""" +{"pack":{"description":"Generated","pack_format":4}} + """.trimIndent()) + } + /*val manifestFile = architectFolder.resolve("META-INF/MANIFEST.MF") + manifestFile.parentFile.mkdirs() + manifestFile.writeText(""" +Manifest-Version: 1.0 +FMLModType: LIBRARY + + """.trimIndent())*/ + + val remapper = remapperBuilder.build() + + try { + OutputConsumerPath.Builder(output).build().use { outputConsumer -> + outputConsumer.addNonClassFiles(input, NonClassCopyMode.SKIP_META_INF, null) + outputConsumer.addNonClassFiles(architectFolder.toPath(), NonClassCopyMode.UNCHANGED, null) + remapper.readClassPath(*classpath) + remapper.readInputs(input) + remapper.apply(outputConsumer) + + if (fakeMod) { + val className = "generated/$fakeModId" + val classWriter = ClassWriter(0) + classWriter.visit(52, Opcodes.ACC_PUBLIC, className, null, "java/lang/Object", null) + val mixinAnnotation = classWriter.visitAnnotation("Lnet/minecraftforge/fml/common/Mod;", false) + mixinAnnotation.visit("value", fakeModId) + mixinAnnotation.visitEnd() + classWriter.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, arrayOf()).also { + it.visitVarInsn(Opcodes.ALOAD, 0) + it.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false) + it.visitInsn(Opcodes.RETURN) + it.visitMaxs(1, 1) + it.visitEnd() + } + classWriter.visitEnd() + outputConsumer.accept(className, classWriter.toByteArray()) + } + } + } catch (e: Exception) { + remapper.finish() + throw RuntimeException("Failed to remap $input to $output", e) + } + + architectFolder.deleteRecursively() + remapper.finish() + + if (!Files.exists(output)) { + throw RuntimeException("Failed to remap $input to $output - file missing!") + } + } + + private fun remapToMcp(parent: IMappingProvider, mojmapToMcpClass: Map): IMappingProvider = IMappingProvider { + it.acceptClass("net/fabricmc/api/Environment", "net/minecraftforge/api/distmarker/OnlyIn") + it.acceptClass("net/fabricmc/api/EnvType", "net/minecraftforge/api/distmarker/Dist") + it.acceptField(IMappingProvider.Member("net/fabricmc/api/EnvType", "SERVER", "Lnet/fabricmc/api/EnvType;"), "DEDICATED_SERVER") + + parent.load(object : IMappingProvider.MappingAcceptor { + override fun acceptClass(srcName: String?, dstName: String?) { + it.acceptClass(srcName, mojmapToMcpClass[srcName] ?: srcName) + } + + override fun acceptMethod(method: IMappingProvider.Member?, dstName: String?) { + } + + override fun acceptMethodArg(method: IMappingProvider.Member?, lvIndex: Int, dstName: String?) { + } + + override fun acceptMethodVar(method: IMappingProvider.Member?, lvIndex: Int, startOpIdx: Int, asmIndex: Int, dstName: String?) { + } + + override fun acceptField(field: IMappingProvider.Member?, dstName: String?) { + } + }) + } + + private fun getMappings(): TinyTree { + val loomExtension = project.extensions.getByType(LoomGradleExtension::class.java) + return loomExtension.mappingsProvider.mappings + } + + private fun getRootExtension(): ArchitectPluginExtension = + project.rootProject.extensions.getByType(ArchitectPluginExtension::class.java) + + private fun createMojmapToMcpClass(mappings: TinyTree): Map { + val mcpMappings = readMCPMappings(getRootExtension().minecraft) + val mutableMap = mutableMapOf() + mappings.classes.forEach { clazz -> + val official = clazz.getName("official") + val named = clazz.getName("named") + val mcp = mcpMappings[official] + if (mcp != null) { + mutableMap[named] = mcp + } + } + return mutableMap + } + + private fun readMCPMappings(version: String): Map { + val file = project.rootProject.file(".gradle/mappings/mcp-$version.tsrg") + if (file.exists().not()) { + file.parentFile.mkdirs() + file.writeText(URL("https://raw.githubusercontent.com/MinecraftForge/MCPConfig/master/versions/release/$version/joined.tsrg").readText()) + } + return mutableMapOf().also { readMappings(it, file.inputStream()) } + } + + private fun readMappings(mutableMap: MutableMap, inputStream: InputStream) { + inputStream.bufferedReader().forEachLine { + if (!it.startsWith("\t")) { + val split = it.split(" ") + val obf = split[0] + val className = split[1] + mutableMap[obf] = className + } + } + } +} \ No newline at end of file