diff --git a/.github/workflows/build-prs.yml b/.github/workflows/build-prs.yml index 681bd716..21e4db2c 100644 --- a/.github/workflows/build-prs.yml +++ b/.github/workflows/build-prs.yml @@ -28,8 +28,9 @@ jobs: strategy: matrix: os: [ubuntu-latest, windows-latest] + project: [testproject, legacytest] runs-on: ${{ matrix.os }} - name: Test on ${{ matrix.os }} + name: Test ${{ matrix.project }} on ${{ matrix.os }} steps: - name: Checkout project sources uses: actions/checkout@v4 @@ -47,12 +48,12 @@ jobs: - name: Run build run: ./gradlew build neoForgeIdeSync - working-directory: ./testproject + working-directory: ./${{ matrix.project }} - name: Ensure clean, build and test work in the same run run: ./gradlew clean build check - working-directory: ./testproject + working-directory: ./${{ matrix.project }} - name: Ensure runData runs run: ./gradlew runData - working-directory: ./testproject + working-directory: ./${{ matrix.project }} diff --git a/LEGACY.md b/LEGACY.md new file mode 100644 index 00000000..a1459c1f --- /dev/null +++ b/LEGACY.md @@ -0,0 +1,100 @@ +# ModDevGradle Legacy Plugin +ModDevGradle has a secondary plugin (ID: `net.neoforged.moddevgradle.legacy`, released alongside the normal plugin with the same version) +that adds support for developing mods against MinecraftForge and Vanilla Minecraft versions 1.17 up to 1.20.1. + +The legacy plugin is an "addon" plugin, meaning it operates on top of the normal plugin. This means that the APIs normally used +are also available when using the legacy plugin. + +## Basic Usage for MinecraftForge Mods +An example `build.gradle` file for developing a mod against MinecraftForge for 1.20.1 is provided below: +```groovy +plugins { + // Apply the plugin. You can find the latest version at https://projects.neoforged.net/neoforged/ModDevGradle + id 'net.neoforged.moddev.legacy' version '2.0.28-beta' +} + +neoForge { + // Develop against MinecraftForge version 47.3.0 for 1.20.1 (the versions can be found at https://files.minecraftforge.net/) + version = "1.20.1-47.3.0" + + // Validate AT files and raise errors when they have invalid targets + // This option is false by default, but turning it on is recommended + validateAccessTransformers = true + + runs { + client { + client() + } + data { + data() + } + server { + server() + } + } + + mods { + testproject { + sourceSet sourceSets.main + } + } +} +``` + +## Reobfuscating artifacts +Forge used SRG mappings as intermediary mappings in 1.20.1 and below. While your mod is developed against the mappings provided +by Mojang (known as official mappings), you need to reobfuscate it to SRG mappings for it to work in production. +Reobfuscation will automatically be configured for the `jar` task; the non-obfuscated jar will have a `-dev` classifier +and will not be published in favour of the reobfuscated variant. You should upload the `reobfJar` task's output when using a +task to upload to a mod hosting platform, or otherwise the jar without a `-dev` classifier if you're uploading it manually. + +You may reobfuscate other jar tasks using `obfuscation.reobfuscate(TaskProvider, SourceSet, Action)`. +For instance, if you want to reobfuscate a `shadowJar` task: +```groovy +shadowJar { + // Change the classifier of the shadow jar to be -dev-all as it's not mapped in intermediary and not usable for production + archiveClassifier = 'dev-all' +} + +obfuscation { + // Reobfuscate the shadowJar task, using the classpath of the main sourceset for properly remapping inherited members + reobfuscate(tasks.named('shadowJar'), sourceSets.main) { + // Make the reobfuscated shadowJar have the all classifier + // You could also change it to an empty string if you want it to not have a classifier (in that case, you will also need to change the classifier of the slim `reobfJar` task + archiveClassifier = 'all' + } +} +``` + +When reobfuscating a jar, it will be replaced in publications with the obfuscated version to avoid publishing jars that aren't mapped to SRG. + +## Remapping mod dependencies +As published mods are using intermediary mappings, you must remap them to official mappings before being able to use them as a dependencies. +ModDevGradle creates configurations that will automatically remap dependencies added to them from SRG mappings to official mappings. +The following configurations are created automatically and are children of the configurations without the `mod` prefix: +- `modImplementation` +- `modRuntimeOnly` +- `modCompileOnly` +- `modApi` (only if the `java-library` plugin is applied) +- `modCompileOnlyApi` (only if the `java-library` plugin is applied) + +You may create your own remapping configurations using `obfuscation.createRemappingConfiguration(Configuration)`: +```groovy +configurations { + // Create a custom configuration named "custom" + custom +} + +obfuscation { + // Create a configuration named "modCustom" that remaps its dependencies and then adds them to the "custom" configuration + createRemappingConfiguration(configurations.custom) +} +``` + +## Effects of applying the legacy plugin +When applied, the legacy plugin will change the base NeoForm and NeoForge artifact coordinates of the `neoForge` extension to +`de.oceanlabs.mcp:mcp_config` and `net.minecraftforge:forge`. +It will also trigger the creation of various intermediary (SRG) to named (official) mapping files used by various parts of the toolchain, such as +mod reobfuscation and runtime naming services. +Reobfuscation to the intermediary mappings will automatically be configured for the `jar` task, the non-obfuscated jar will have a `-dev` classifier +and will not be published in favour of the reobfuscated variant. diff --git a/build.gradle b/build.gradle index a6f51f7a..9d9b59e6 100644 --- a/build.gradle +++ b/build.gradle @@ -70,6 +70,7 @@ sourceSets { compileClasspath += java8.output runtimeClasspath += java8.output } + legacy } configurations { @@ -77,6 +78,7 @@ configurations { shaded // Place shaded dependencies into `compileOnly` so that they do not leak into our publications' dependencies. compileOnly.extendsFrom shaded + legacyCompileOnly.extendsFrom shaded testCompileOnly.extendsFrom shaded testRuntimeOnly.extendsFrom shaded shadowRuntimeElements { @@ -123,6 +125,10 @@ dependencies { testImplementation gradleTestKit() testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + + legacyImplementation(sourceSets.main.output) + legacyImplementation(sourceSets.java8.output) + legacyImplementation gradleApi() } java { @@ -135,12 +141,14 @@ java { jar { archiveClassifier = 'slim' from sourceSets.java8.output + from sourceSets.legacy.output } shadowJar { archiveClassifier = "" // Required for the Plugin Publish Plugin to publish this jar from sourceSets.java8.output + from sourceSets.legacy.output configurations = [project.configurations.shaded] enableRelocation = true @@ -188,6 +196,13 @@ gradlePlugin { description = "This plugin helps you create Minecraft mods using the NeoForge platform" tags = ["minecraft", "neoforge", "java", "mod"] } + legacy { + id = 'net.neoforged.moddev.legacy' + implementationClass = 'net.neoforged.moddevgradle.boot.LegacyModDevPlugin' + displayName = "NeoForge Legacy Mod Development Plugin" + description = "This plugin helps you create Minecraft mods using the Forge platform, up to 1.20.1" + tags = ["minecraft", "neoforge", "forge", "java", "mod"] + } repositories { id = 'net.neoforged.moddev.repositories' implementationClass = 'net.neoforged.moddevgradle.boot.RepositoriesPlugin' @@ -212,21 +227,7 @@ artifacts { publishing { repositories { - maven { - name = 'NeoForge' - if (System.getenv('MAVEN_USER') && System.getenv('MAVEN_PASSWORD')) { - it.url = "https://maven.neoforged.net/releases/" - it.authentication { - it.create('basic', BasicAuthentication) - } - it.credentials { credentials -> - credentials.username = System.getenv('MAVEN_USER') - credentials.password = System.getenv('MAVEN_PASSWORD') - } - } else { - it.url = 'file://' + file("repo").getAbsolutePath() - } - } + maven(gradleutils.publishingMaven) } } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 2c352119..a4b76b95 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 dedd5d1e..9355b415 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 diff --git a/legacytest/build.gradle b/legacytest/build.gradle new file mode 100644 index 00000000..12e2ef4e --- /dev/null +++ b/legacytest/build.gradle @@ -0,0 +1,41 @@ +plugins { + id 'maven-publish' + id 'net.neoforged.moddev.legacy' +} + +group = 'com.example.legacy' +version = '1.0.0' + +repositories { + mavenLocal() + maven { + name 'cursemaven' + url 'https://cursemaven.com' + content { + includeGroup "curse.maven" + } + } +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +neoForge { + neoFormVersion = '1.19.2' +} + +publishing { + publications { + maven(MavenPublication) { + from components.java + } + } + repositories { + maven { + url file('local') + } + } +} diff --git a/legacytest/forge/build.gradle b/legacytest/forge/build.gradle new file mode 100644 index 00000000..fe40c6ac --- /dev/null +++ b/legacytest/forge/build.gradle @@ -0,0 +1,49 @@ +plugins { + id 'net.neoforged.moddev.legacy' +} + +repositories { + mavenLocal() + maven { + name = "Jared's maven" + url = "https://maven.blamejared.com/" + } + maven { + name 'cursemaven' + url 'https://cursemaven.com' + content { + includeGroup "curse.maven" + } + } +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +dependencies { + modCompileOnly('mezz.jei:jei-1.20.1-forge:15.17.0.76') { + transitive = false + } + modRuntimeOnly('curse.maven:mekanism-268560:5662583') + modImplementation('curse.maven:applied-energistics-2-223794:5641282') +} + +neoForge { + version = '1.20.1-47.3.0' + runs { + client { + client() + } + data { + data() + } + } + mods { + myMod { + sourceSet(sourceSets.main) + } + } +} diff --git a/legacytest/forge/src/main/java/mymod/JeiCompat.java b/legacytest/forge/src/main/java/mymod/JeiCompat.java new file mode 100644 index 00000000..36fc21e3 --- /dev/null +++ b/legacytest/forge/src/main/java/mymod/JeiCompat.java @@ -0,0 +1,20 @@ +package mymod; + +import mezz.jei.api.IModPlugin; +import mezz.jei.api.JeiPlugin; +import mezz.jei.api.registration.ISubtypeRegistration; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.Items; + +@JeiPlugin +public class JeiCompat implements IModPlugin { + @Override + public ResourceLocation getPluginUid() { + return new ResourceLocation("mymod:mymod"); + } + + @Override + public void registerItemSubtypes(ISubtypeRegistration registration) { + registration.registerSubtypeInterpreter(Items.ALLIUM, (ingredient, context) -> "allium"); + } +} diff --git a/legacytest/forge/src/main/java/mymod/MyMod.java b/legacytest/forge/src/main/java/mymod/MyMod.java new file mode 100644 index 00000000..c62f187e --- /dev/null +++ b/legacytest/forge/src/main/java/mymod/MyMod.java @@ -0,0 +1,9 @@ +package mymod; + +import net.minecraftforge.fml.common.Mod; + +@Mod("mymod") +public class MyMod { + public void run() { + } +} diff --git a/legacytest/forge/src/main/resources/META-INF/mods.toml b/legacytest/forge/src/main/resources/META-INF/mods.toml new file mode 100644 index 00000000..0843d268 --- /dev/null +++ b/legacytest/forge/src/main/resources/META-INF/mods.toml @@ -0,0 +1,12 @@ +modLoader="javafml" #mandatory +loaderVersion="*" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions. +license="ARR" +[[mods]] #mandatory +# The modid of the mod +modId="mymod" #mandatory +# The version number of the mod +version="1.0" #mandatory +# A display name for the mod +displayName="My Mod" #mandatory +authors="MDG" #optional +description='''Hi.''' diff --git a/legacytest/gradle.properties b/legacytest/gradle.properties new file mode 100644 index 00000000..5ad69748 --- /dev/null +++ b/legacytest/gradle.properties @@ -0,0 +1 @@ +org.gradle.configuration-cache=true diff --git a/legacytest/gradle/wrapper/gradle-wrapper.jar b/legacytest/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..a4b76b95 Binary files /dev/null and b/legacytest/gradle/wrapper/gradle-wrapper.jar differ diff --git a/legacytest/gradle/wrapper/gradle-wrapper.properties b/legacytest/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..66cd5a0e --- /dev/null +++ b/legacytest/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/legacytest/gradlew b/legacytest/gradlew new file mode 100755 index 00000000..1aa94a42 --- /dev/null +++ b/legacytest/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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 POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# 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 +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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 + 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. +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=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# 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" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/legacytest/gradlew.bat b/legacytest/gradlew.bat new file mode 100644 index 00000000..93e3f59f --- /dev/null +++ b/legacytest/gradlew.bat @@ -0,0 +1,92 @@ +@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=. +@rem This is normally unused +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% 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. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +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. + +goto fail + +: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 %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/legacytest/settings.gradle b/legacytest/settings.gradle new file mode 100644 index 00000000..31c788ef --- /dev/null +++ b/legacytest/settings.gradle @@ -0,0 +1,4 @@ + +includeBuild '..' + +include 'forge' diff --git a/legacytest/src/main/java/legacytest/LegacyTest.java b/legacytest/src/main/java/legacytest/LegacyTest.java new file mode 100644 index 00000000..1496c7e1 --- /dev/null +++ b/legacytest/src/main/java/legacytest/LegacyTest.java @@ -0,0 +1,19 @@ +package legacytest; + +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.DetectedVersion; +import net.minecraft.client.main.Main; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +public class LegacyTest { + public static void main(String[] args) { + System.out.println(DetectedVersion.tryDetectVersion()); + Main.main(new String[]{ + + }); + + System.out.println(new ItemStack(Items.ACACIA_LEAVES).getCount()); + RenderSystem.disableBlend(); + } +} diff --git a/src/java8/java/net/neoforged/moddevgradle/boot/LegacyModDevPlugin.java b/src/java8/java/net/neoforged/moddevgradle/boot/LegacyModDevPlugin.java new file mode 100644 index 00000000..e8fd0f65 --- /dev/null +++ b/src/java8/java/net/neoforged/moddevgradle/boot/LegacyModDevPlugin.java @@ -0,0 +1,9 @@ +package net.neoforged.moddevgradle.boot; + +import org.gradle.api.Project; + +public class LegacyModDevPlugin extends TrampolinePlugin { + public LegacyModDevPlugin() { + super("net.neoforged.moddevgradle.legacy.LegacyModDevPlugin"); + } +} diff --git a/src/legacy/java/net/neoforged/moddevgradle/internal/LegacyInternal.java b/src/legacy/java/net/neoforged/moddevgradle/internal/LegacyInternal.java new file mode 100644 index 00000000..0e8d8080 --- /dev/null +++ b/src/legacy/java/net/neoforged/moddevgradle/internal/LegacyInternal.java @@ -0,0 +1,10 @@ +package net.neoforged.moddevgradle.internal; + +import net.neoforged.moddevgradle.dsl.RunModel; +import org.gradle.api.Project; + +public class LegacyInternal { + public static void configureRun(Project project, RunModel run) { + run.getEnvironment().put("MOD_CLASSES", RunUtils.getGradleModFoldersProvider(project, run.getMods(), false).getClassesArgument()); + } +} diff --git a/src/legacy/java/net/neoforged/moddevgradle/legacy/LegacyForgeMetadataTransform.java b/src/legacy/java/net/neoforged/moddevgradle/legacy/LegacyForgeMetadataTransform.java new file mode 100644 index 00000000..427981c1 --- /dev/null +++ b/src/legacy/java/net/neoforged/moddevgradle/legacy/LegacyForgeMetadataTransform.java @@ -0,0 +1,106 @@ +package net.neoforged.moddevgradle.legacy; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.gradle.api.Action; +import org.gradle.api.artifacts.ComponentMetadataContext; +import org.gradle.api.artifacts.DirectDependenciesMetadata; +import org.gradle.api.artifacts.DirectDependencyMetadata; +import org.gradle.api.artifacts.MutableVariantFilesMetadata; +import org.gradle.api.artifacts.repositories.RepositoryResourceAccessor; +import org.gradle.api.attributes.Bundling; +import org.gradle.api.attributes.Category; +import org.gradle.api.attributes.Usage; +import org.gradle.api.model.ObjectFactory; + +import javax.inject.Inject; + +// @CacheableTransform +class LegacyForgeMetadataTransform extends LegacyMetadataTransform { + @Inject + public LegacyForgeMetadataTransform(ObjectFactory objects, RepositoryResourceAccessor repositoryResourceAccessor) { + super(objects, repositoryResourceAccessor); + } + + @Override + public void execute(ComponentMetadataContext context) { + executeWithConfig(context, createPath(context, "userdev", "jar")); + } + + @Override + public void adaptWithConfig(ComponentMetadataContext context, JsonObject config) { + var details = context.getDetails(); + var id = details.getId(); + + var userdevJarName = id.getName() + "-" + id.getVersion() + "-userdev.jar"; + + Action vanillaDependencies = deps -> { + deps.add("de.oceanlabs.mcp:mcp_config:" + id.getVersion().split("-")[0]); + deps.add("net.neoforged:minecraft-dependencies:" + id.getVersion().split("-")[0]); + }; + + details.addVariant("modDevConfig", variantMetadata -> { + variantMetadata.withFiles(metadata -> metadata.addFile(userdevJarName, userdevJarName)); + variantMetadata.withCapabilities(capabilities -> { + capabilities.addCapability("net.neoforged", "neoforge-moddev-config", id.getVersion()); + }); + }); + details.addVariant("modDevBundle", variantMetadata -> { + variantMetadata.withFiles(metadata -> metadata.addFile(userdevJarName, userdevJarName)); + variantMetadata.withDependencies(vanillaDependencies); + variantMetadata.withCapabilities(capabilities -> { + capabilities.addCapability("net.neoforged", "neoforge-moddev-bundle", id.getVersion()); + }); + }); + details.addVariant("modDevModulePath", variantMetadata -> { + variantMetadata.withDependencies(dependencies -> { + var modules = config.getAsJsonArray("modules"); + for (JsonElement module : modules) { + dependencies.add(module.getAsString()); + } + }); + variantMetadata.withCapabilities(capabilities -> { + capabilities.addCapability("net.neoforged", "neoforge-moddev-module-path", id.getVersion()); + }); + }); + details.addVariant("modDevApiElements", variantMetadata -> { + variantMetadata.attributes(attributes -> { + attributes.attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category.class, Category.LIBRARY)); + attributes.attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.class, Bundling.EXTERNAL)); + attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.class, Usage.JAVA_API)); + }); + variantMetadata.withDependencies(dependencies -> { + var libraries = config.getAsJsonArray("libraries"); + for (JsonElement library : libraries) { + dependencies.add(library.getAsString()); + } + }); + variantMetadata.withDependencies(vanillaDependencies); + variantMetadata.withCapabilities(capabilities -> { + capabilities.addCapability("net.neoforged", "neoforge-dependencies", id.getVersion()); + }); + }); + details.withVariant("runtime", variantMetadata -> { + variantMetadata.attributes(attributes -> { + attributes.attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category.class, Category.LIBRARY)); + attributes.attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.class, Bundling.EXTERNAL)); + attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.class, Usage.JAVA_RUNTIME)); + }); + variantMetadata.withCapabilities(capabilities -> { + capabilities.addCapability("net.neoforged", "neoforge-dependencies", id.getVersion()); + }); + variantMetadata.withDependencies(vanillaDependencies); + variantMetadata.withFiles(MutableVariantFilesMetadata::removeAllFiles); + variantMetadata.withDependencies(dependencies -> { + var modules = config.getAsJsonArray("modules"); + for (JsonElement module : modules) { + dependencies.add(module.getAsString()); + } + var libraries = config.getAsJsonArray("libraries"); + for (JsonElement library : libraries) { + dependencies.add(library.getAsString()); + } + }); + }); + } +} diff --git a/src/legacy/java/net/neoforged/moddevgradle/legacy/LegacyMetadataTransform.java b/src/legacy/java/net/neoforged/moddevgradle/legacy/LegacyMetadataTransform.java new file mode 100644 index 00000000..34e44fad --- /dev/null +++ b/src/legacy/java/net/neoforged/moddevgradle/legacy/LegacyMetadataTransform.java @@ -0,0 +1,52 @@ +package net.neoforged.moddevgradle.legacy; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.gradle.api.GradleException; +import org.gradle.api.artifacts.ComponentMetadataContext; +import org.gradle.api.artifacts.ComponentMetadataRule; +import org.gradle.api.artifacts.repositories.RepositoryResourceAccessor; +import org.gradle.api.model.ObjectFactory; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.jar.JarInputStream; + +abstract class LegacyMetadataTransform implements ComponentMetadataRule { + protected final ObjectFactory objects; + private final RepositoryResourceAccessor repositoryResourceAccessor; + + LegacyMetadataTransform(ObjectFactory objects, RepositoryResourceAccessor repositoryResourceAccessor) { + this.objects = objects; + this.repositoryResourceAccessor = repositoryResourceAccessor; + } + + protected final void executeWithConfig(ComponentMetadataContext context, String path) { + JsonObject[] configRootHolder = new JsonObject[1]; + repositoryResourceAccessor.withResource(path, inputStream -> { + try (var zin = new JarInputStream(new BufferedInputStream(inputStream))) { + for (var entry = zin.getNextJarEntry(); entry != null; entry = zin.getNextJarEntry()) { + if (entry.getName().equals("config.json")) { + var configJson = new String(zin.readAllBytes(), StandardCharsets.UTF_8); + configRootHolder[0] = new Gson().fromJson(configJson, JsonObject.class); + } + } + } catch (IOException e) { + throw new GradleException("Failed to read " + path); + } + }); + + if (configRootHolder[0] == null) { + throw new GradleException("Couldn't find config.json in " + path); + } + adaptWithConfig(context, configRootHolder[0]); + } + + protected abstract void adaptWithConfig(ComponentMetadataContext context, JsonObject config); + + protected final String createPath(ComponentMetadataContext context, String classifier, String extension) { + var id = context.getDetails().getId(); + return id.getGroup().replace('.', '/') + "/" + id.getName() + "/" + id.getVersion() + "/" + (id.getName() + "-" + id.getVersion() + (classifier.isBlank() ? "" : "-" + classifier) + "." + extension); + } +} diff --git a/src/legacy/java/net/neoforged/moddevgradle/legacy/LegacyModDevPlugin.java b/src/legacy/java/net/neoforged/moddevgradle/legacy/LegacyModDevPlugin.java new file mode 100644 index 00000000..c33350c8 --- /dev/null +++ b/src/legacy/java/net/neoforged/moddevgradle/legacy/LegacyModDevPlugin.java @@ -0,0 +1,135 @@ +package net.neoforged.moddevgradle.legacy; + +import net.neoforged.moddevgradle.dsl.NeoForgeExtension; +import net.neoforged.moddevgradle.internal.LegacyInternal; +import net.neoforged.moddevgradle.internal.ModDevPlugin; +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.api.artifacts.type.ArtifactTypeDefinition; +import org.gradle.api.attributes.Attribute; +import org.gradle.api.file.RegularFile; +import org.gradle.api.plugins.JavaPlugin; +import org.gradle.api.tasks.SourceSet; +import org.gradle.api.tasks.SourceSetContainer; +import org.gradle.jvm.tasks.Jar; + +import java.net.URI; +import java.util.Map; +import java.util.stream.Stream; + +public class LegacyModDevPlugin implements Plugin { + public static final Attribute REMAPPED = Attribute.of("net.neoforged.moddevgradle.legacy.remapped", Boolean.class); + + @Override + public void apply(Project project) { + project.getPlugins().apply(ModDevPlugin.class); + + project.getRepositories().maven(repo -> { + repo.setName("MinecraftForge"); + repo.setUrl(URI.create("https://maven.minecraftforge.net/")); + }); + + project.getDependencies().getComponents().withModule("net.neoforged:forge", LegacyForgeMetadataTransform.class); + project.getDependencies().getComponents().withModule("net.minecraftforge:forge", LegacyForgeMetadataTransform.class); + project.getDependencies().getComponents().withModule("de.oceanlabs.mcp:mcp_config", McpMetadataTransform.class); + + var depFactory = project.getDependencyFactory(); + var autoRenamingToolRuntime = project.getConfigurations().create("autoRenamingToolRuntime", spec -> { + spec.setDescription("The AutoRenamingTool CLI tool"); + spec.setCanBeConsumed(false); + spec.setCanBeResolved(true); + spec.setTransitive(false); + spec.defaultDependencies(dependencies -> dependencies.add(depFactory.create("net.neoforged:AutoRenamingTool:2.0.4:all"))); + }); + var installerToolsRuntime = project.getConfigurations().create("installerToolsRuntime", spec -> { + spec.setDescription("The InstallerTools CLI tool"); + spec.setCanBeConsumed(false); + spec.setCanBeResolved(true); + spec.setTransitive(false); + spec.defaultDependencies(dependencies -> dependencies.add(depFactory.create("net.neoforged.installertools:installertools:2.1.7:fatjar"))); + }); + + // We use this directory to store intermediate files used during moddev + var modDevBuildDir = project.getLayout().getBuildDirectory().dir("moddev"); + var namedToIntermediate = modDevBuildDir.map(d -> d.file("namedToIntermediate.tsrg")); + var intermediateToNamed = modDevBuildDir.map(d -> d.file("intermediateToNamed.srg")); + var mappingsCsv = modDevBuildDir.map(d -> d.file("intermediateToNamed.zip")); + + var obf = project.getExtensions().create("obfuscation", Obfuscation.class, project, namedToIntermediate, mappingsCsv, autoRenamingToolRuntime, installerToolsRuntime); + var mixin = project.getExtensions().create("mixin", MixinExtension.class, project, namedToIntermediate); + + project.getExtensions().configure(NeoForgeExtension.class, extension -> { + extension.getNeoForgeArtifact().set(extension.getVersion().map(version -> "net.minecraftforge:forge:" + version)); + extension.getNeoFormArtifact().set(extension.getNeoFormVersion().map(version -> "de.oceanlabs.mcp:mcp_config:" + version)); + + extension.getNeoFormRuntime().getAdditionalResults().put("namedToIntermediaryMapping", namedToIntermediate.map(RegularFile::getAsFile)); + extension.getNeoFormRuntime().getAdditionalResults().put("intermediaryToNamedMapping", intermediateToNamed.map(RegularFile::getAsFile)); + extension.getNeoFormRuntime().getAdditionalResults().put("csvMapping", mappingsCsv.map(RegularFile::getAsFile)); + + extension.getRuns().configureEach(run -> { + LegacyInternal.configureRun(project, run); + + // Mixin needs the intermediate (SRG) -> named (Mojang, MCP) mapping file in SRG (TSRG is not supported) to be able to ignore the refmaps of dependencies + run.getSystemProperties().put("mixin.env.remapRefMap", "true"); + run.getSystemProperties().put("mixin.env.refMapRemappingFile", intermediateToNamed.map(f -> f.getAsFile().getAbsolutePath())); + + run.getProgramArguments().addAll(mixin.getConfigs().map(cfgs -> cfgs.stream().flatMap(config -> Stream.of("--mixin.config", config)).toList())); + }); + }); + + var reobfJar = obf.reobfuscate( + project.getTasks().named(JavaPlugin.JAR_TASK_NAME, Jar.class), + project.getExtensions().getByType(SourceSetContainer.class).getByName(SourceSet.MAIN_SOURCE_SET_NAME), + remapJarTask -> remapJarTask.getArchiveClassifier().set("") + ); + + project.getTasks().named(JavaPlugin.JAR_TASK_NAME, Jar.class).configure(jar -> jar.getArchiveClassifier().set("dev")); + project.getTasks().named("assemble", assemble -> assemble.dependsOn(reobfJar)); + + // Forge expects the mapping csv files on the root classpath + project.getConfigurations().getByName(ModDevPlugin.CONFIGURATION_RUNTIME_DEPENDENCIES) + .getDependencies().add(project.getDependencyFactory().create(project.files(mappingsCsv))); + + // Forge expects to find the Forge and client-extra jar on the legacy classpath + project.getConfigurations().getByName("additionalRuntimeClasspath") + .extendsFrom(project.getConfigurations().getByName(ModDevPlugin.CONFIGURATION_RUNTIME_DEPENDENCIES)) + .exclude(Map.of("group", "net.neoforged", "module", "DevLaunch")); + + project.getDependencies().attributesSchema(schema -> schema.attribute(REMAPPED)); + project.getDependencies().getArtifactTypes().named("jar", a -> a.getAttributes().attribute(REMAPPED, false)); + + var remapDeps = project.getConfigurations().create("remappingDependencies", spec -> { + spec.setDescription("An internal configuration that contains the Minecraft dependencies, used for remapping mods"); + spec.setCanBeConsumed(false); + spec.setCanBeDeclared(false); + spec.setCanBeResolved(true); + spec.extendsFrom(project.getConfigurations().getByName(ModDevPlugin.CONFIGURATION_RUNTIME_DEPENDENCIES)); + }); + + project.getDependencies().registerTransform(RemappingTransform.class, params -> { + params.parameters(parameters -> { + parameters.getParameters().set(project.provider(() -> { + var p = project.getObjects().newInstance(RemapParameters.class); + p.from(obf, RemapParameters.ToolType.INSTALLER_TOOLS); + return p; + })); + parameters.getMinecraftDependencies().from(remapDeps); + }); + params.getFrom() + .attribute(REMAPPED, false) + .attribute(ArtifactTypeDefinition.ARTIFACT_TYPE_ATTRIBUTE, ArtifactTypeDefinition.JAR_TYPE); + params.getTo() + .attribute(REMAPPED, true) + .attribute(ArtifactTypeDefinition.ARTIFACT_TYPE_ATTRIBUTE, ArtifactTypeDefinition.JAR_TYPE); + }); + + obf.createRemappingConfiguration(project.getConfigurations().getByName(JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME)); + obf.createRemappingConfiguration(project.getConfigurations().getByName(JavaPlugin.RUNTIME_ONLY_CONFIGURATION_NAME)); + obf.createRemappingConfiguration(project.getConfigurations().getByName(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME)); + + project.getPlugins().withId("java-library", plugin -> { + obf.createRemappingConfiguration(project.getConfigurations().getByName(JavaPlugin.API_CONFIGURATION_NAME)); + obf.createRemappingConfiguration(project.getConfigurations().getByName(JavaPlugin.COMPILE_ONLY_API_CONFIGURATION_NAME)); + }); + } +} diff --git a/src/legacy/java/net/neoforged/moddevgradle/legacy/McpMetadataTransform.java b/src/legacy/java/net/neoforged/moddevgradle/legacy/McpMetadataTransform.java new file mode 100644 index 00000000..6cc8d7d2 --- /dev/null +++ b/src/legacy/java/net/neoforged/moddevgradle/legacy/McpMetadataTransform.java @@ -0,0 +1,88 @@ +package net.neoforged.moddevgradle.legacy; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.gradle.api.Action; +import org.gradle.api.artifacts.ComponentMetadataContext; +import org.gradle.api.artifacts.DirectDependenciesMetadata; +import org.gradle.api.artifacts.repositories.RepositoryResourceAccessor; +import org.gradle.api.attributes.Usage; +import org.gradle.api.attributes.java.TargetJvmVersion; +import org.gradle.api.model.ObjectFactory; + +import javax.inject.Inject; + +/** + * Given an implicit Metadata object by Gradle (which results from reading in a pom.xml from Maven for MCP data, + * which is basically empty), we build metadata that is equivalent to NeoForms Gradle module metadata. + *

+ * Example for NeoForm: + * https://maven.neoforged.net/releases/net/neoforged/neoform/1.21-20240613.152323/neoform-1.21-20240613.152323.module + */ +// @CacheableTransform +class McpMetadataTransform extends LegacyMetadataTransform { + @Inject + public McpMetadataTransform(ObjectFactory objects, RepositoryResourceAccessor repositoryResourceAccessor) { + super(objects, repositoryResourceAccessor); + } + + @Override + public void execute(ComponentMetadataContext context) { + executeWithConfig(context, createPath(context, "", "zip")); + } + + @Override + protected void adaptWithConfig(ComponentMetadataContext context, JsonObject config) { + var details = context.getDetails(); + var id = details.getId(); + + var zipDataName = id.getName() + "-" + id.getVersion() + ".zip"; + + var javaTarget = config.getAsJsonPrimitive("java_target").getAsInt(); + + // a.k.a. "neoformData" + // Primarily pulled to use for NFRT manifest + details.addVariant("mcpData", variantMetadata -> { + variantMetadata.withFiles(files -> files.addFile(zipDataName)); + variantMetadata.attributes(attributes -> { + attributes.attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, javaTarget); + }); + // Add tools required by this version of MCP as dependencies of this variant + variantMetadata.withDependencies(dependencies -> { + var functions = config.getAsJsonObject("functions"); + for (var function : functions.entrySet()) { + var toolCoordinate = ((JsonObject) function.getValue()).getAsJsonPrimitive("version").getAsString(); + dependencies.add(toolCoordinate); + } + }); + variantMetadata.withCapabilities(capabilities -> { + capabilities.addCapability("net.neoforged", "neoform", id.getVersion()); + }); + }); + + dependencies(context, "mcpRuntimeElements", javaTarget, Usage.JAVA_RUNTIME, deps -> {}); + + dependencies(context, "mcpApiElements", javaTarget, Usage.JAVA_API, dependencies -> { + var libraries = config.getAsJsonObject("libraries").getAsJsonArray("joined"); + for (JsonElement library : libraries) { + dependencies.add(library.getAsString()); + } + }); + } + + private void dependencies(ComponentMetadataContext context, String name, int javaTarget, String usage, Action deps) { + context.getDetails().addVariant(name, variantMetadata -> { + variantMetadata.attributes(attributes -> { + attributes.attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, javaTarget); + attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.class, usage)); + }); + variantMetadata.withDependencies(dependencies -> { + deps.execute(dependencies); + dependencies.add("net.neoforged:minecraft-dependencies:" + context.getDetails().getId().getVersion()); + }); + variantMetadata.withCapabilities(capabilities -> { + capabilities.addCapability("net.neoforged", "neoform-dependencies", context.getDetails().getId().getVersion()); + }); + }); + } +} diff --git a/src/legacy/java/net/neoforged/moddevgradle/legacy/MixinExtension.java b/src/legacy/java/net/neoforged/moddevgradle/legacy/MixinExtension.java new file mode 100644 index 00000000..3e2c4f1f --- /dev/null +++ b/src/legacy/java/net/neoforged/moddevgradle/legacy/MixinExtension.java @@ -0,0 +1,91 @@ +package net.neoforged.moddevgradle.legacy; + +import org.gradle.api.Project; +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.file.RegularFile; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.provider.ListProperty; +import org.gradle.api.provider.Provider; +import org.gradle.api.tasks.InputFile; +import org.gradle.api.tasks.OutputFile; +import org.gradle.api.tasks.PathSensitive; +import org.gradle.api.tasks.PathSensitivity; +import org.gradle.api.tasks.SourceSet; +import org.gradle.api.tasks.compile.JavaCompile; +import org.gradle.jvm.tasks.Jar; +import org.gradle.process.CommandLineArgumentProvider; + +import javax.inject.Inject; +import java.util.List; + +public abstract class MixinExtension { + private final Project project; + private final Provider officialToSrg; + + @Inject + public MixinExtension(Project project, Provider officialToSrg) { + this.project = project; + this.officialToSrg = officialToSrg; + } + + public abstract ListProperty getConfigs(); + + protected abstract ConfigurableFileCollection getExtraMappingFiles(); + + public void config(String name) { + getConfigs().add(name); + } + + public Provider add(SourceSet sourceSet, String refmap) { + var mappingFile = project.getLayout().getBuildDirectory().dir("mixin").map(d -> d.file(refmap + ".mappings.tsrg")); + var refMapFile = project.getLayout().getBuildDirectory().dir("mixin").map(d -> d.file(refmap)); + + var compilerArgs = project.getObjects().newInstance(MixinCompilerArgs.class); + compilerArgs.getRefmap().set(refMapFile); + compilerArgs.getOutMappings().set(mappingFile); + compilerArgs.getInMappings().set(officialToSrg); + + getExtraMappingFiles().from(mappingFile); + + project.getTasks().named(sourceSet.getCompileJavaTaskName(), JavaCompile.class).configure(compile -> { + compile.getOptions().getCompilerArgumentProviders().add(compilerArgs); + }); + + // We use matching because there's no guarantee each sourceset will have a jar task + project.getTasks().withType(Jar.class).matching(jar -> jar.getName().equals(sourceSet.getJarTaskName())).configureEach(jar -> { + jar.from(refMapFile); + }); + + return refMapFile; + } +} + +abstract class MixinCompilerArgs implements CommandLineArgumentProvider { + @Inject + public MixinCompilerArgs() {} + + @OutputFile + protected abstract RegularFileProperty getOutMappings(); + + @OutputFile + protected abstract RegularFileProperty getRefmap(); + + /** + * {@return official -> SRG TSRGv2 mappings file of the game} + */ + @InputFile + @PathSensitive(PathSensitivity.NAME_ONLY) + protected abstract RegularFileProperty getInMappings(); + + @Override + public Iterable asArguments() { + return List.of( + "-AreobfTsrgFile=" + getInMappings().get().getAsFile().getAbsolutePath(), + "-AoutTsrgFile=" + getOutMappings().get().getAsFile().getAbsolutePath(), + "-AoutRefMapFile=" + getRefmap().get().getAsFile().getAbsolutePath(), + "-AmappingTypes=tsrg", + "-ApluginVersion=0.7", // Not sure what this is used for, but MixinGradle gives it to the AP. Latest as of time of writing + "-AdefaultObfuscationEnv=searge" + ); + } +} diff --git a/src/legacy/java/net/neoforged/moddevgradle/legacy/Obfuscation.java b/src/legacy/java/net/neoforged/moddevgradle/legacy/Obfuscation.java new file mode 100644 index 00000000..b741f879 --- /dev/null +++ b/src/legacy/java/net/neoforged/moddevgradle/legacy/Obfuscation.java @@ -0,0 +1,111 @@ +package net.neoforged.moddevgradle.legacy; + +import org.apache.commons.lang3.StringUtils; +import org.gradle.api.Action; +import org.gradle.api.Project; +import org.gradle.api.artifacts.Configuration; +import org.gradle.api.artifacts.ExternalModuleDependency; +import org.gradle.api.artifacts.FileCollectionDependency; +import org.gradle.api.artifacts.ProjectDependency; +import org.gradle.api.component.AdhocComponentWithVariants; +import org.gradle.api.file.RegularFile; +import org.gradle.api.plugins.JavaPlugin; +import org.gradle.api.provider.Provider; +import org.gradle.api.tasks.SourceSet; +import org.gradle.api.tasks.TaskProvider; +import org.gradle.api.tasks.bundling.AbstractArchiveTask; + +import javax.inject.Inject; +import java.util.List; + +public abstract class Obfuscation { + private final Project project; + final Provider officialToSrg, mappingsCsv; + final Configuration autoRenamingToolRuntime; + final Configuration installerToolsRuntime; + + @Inject + public Obfuscation(Project project, Provider officialToSrg, Provider mappingsCsv, Configuration autoRenamingToolRuntime, Configuration installerToolsRuntime) { + this.project = project; + this.officialToSrg = officialToSrg; + this.mappingsCsv = mappingsCsv; + this.autoRenamingToolRuntime = autoRenamingToolRuntime; + this.installerToolsRuntime = installerToolsRuntime; + } + + /** + * Create a configure a reobfuscation task. + * + * @param jar the jar task to reobfuscate + * @param sourceSet the source set whose classpath to use when remapping inherited methods + * @param configuration an action used to configure the rebfuscation task + * @return a provider of the created task + */ + public TaskProvider reobfuscate(TaskProvider jar, SourceSet sourceSet, Action configuration) { + var extraMappings = project.getExtensions().getByType(MixinExtension.class).getExtraMappingFiles(); + var reobf = project.getTasks().register("reobf" + StringUtils.capitalize(jar.getName()), RemapJarTask.class, task -> { + task.getInput().set(jar.flatMap(AbstractArchiveTask::getArchiveFile)); + task.getDestinationDirectory().convention(jar.flatMap(AbstractArchiveTask::getDestinationDirectory)); + task.getArchiveBaseName().convention(jar.flatMap(AbstractArchiveTask::getArchiveBaseName)); + task.getArchiveVersion().convention(jar.flatMap(AbstractArchiveTask::getArchiveVersion)); + task.getArchiveClassifier().convention(jar.flatMap(AbstractArchiveTask::getArchiveClassifier).map(c -> c + "-reobf")); + task.getArchiveAppendix().convention(jar.flatMap(AbstractArchiveTask::getArchiveAppendix)); + task.getLibraries().from(sourceSet.getCompileClasspath()); + task.getParameters().from(this, RemapParameters.ToolType.ART); + task.getParameters().getMappings().from(extraMappings); + configuration.execute(task); + }); + + jar.configure(jarTask -> jarTask.finalizedBy(reobf)); + + var java = (AdhocComponentWithVariants) project.getComponents().getByName("java"); + for (var configurationNames : List.of(JavaPlugin.RUNTIME_ELEMENTS_CONFIGURATION_NAME, JavaPlugin.API_ELEMENTS_CONFIGURATION_NAME)) { + project.getArtifacts().add(configurationNames, reobf); + + java.withVariantsFromConfiguration(project.getConfigurations().getByName(configurationNames), variant -> { + variant.getConfigurationVariant().getArtifacts().removeIf(artifact -> artifact.getFile().equals(jar.get().getArchiveFile().get().getAsFile())); + }); + } + + return reobf; + } + + /** + * Creates a configuration that will remap its dependencies, and adds it as a children of the provided {@code parent}. + */ + public Configuration createRemappingConfiguration(Configuration parent) { + var remappingConfig = project.getConfigurations().create("mod" + StringUtils.capitalize(parent.getName()), spec -> { + spec.setDescription("Configuration for dependencies of " + parent.getName() + " that needs to be remapped"); + spec.attributes(attributeContainer -> { + attributeContainer.attribute(LegacyModDevPlugin.REMAPPED, true); + }); + + // Unfortunately, if we simply try to make the parent extend this config, transformations will not run because the parent doesn't request remapped deps + // If the parent were to request remapped deps, we'd be remapping everything in it. + // Therefore we use a slight "hack" that imposes a constraint over all dependencies in this configuration: to be remapped + spec.withDependencies(dependencies -> dependencies.forEach(dep -> { + if (dep instanceof ExternalModuleDependency externalModuleDependency) { + project.getDependencies().constraints(constraints -> { + constraints.add(parent.getName(), externalModuleDependency.getGroup() + ":" + externalModuleDependency.getName() + ":" + externalModuleDependency.getVersion(), c -> { + c.attributes(a -> a.attribute(LegacyModDevPlugin.REMAPPED, true)); + }); + }); + } else if (dep instanceof FileCollectionDependency fileCollectionDependency) { + project.getDependencies().constraints(constraints -> { + constraints.add(parent.getName(), fileCollectionDependency.getFiles(), c -> { + c.attributes(a -> a.attribute(LegacyModDevPlugin.REMAPPED, true)); + }); + }); + } else if (dep instanceof ProjectDependency projectDependency) { + project.getDependencies().constraints(constraints -> { + constraints.add(parent.getName(), projectDependency.getDependencyProject(), c -> { + c.attributes(a -> a.attribute(LegacyModDevPlugin.REMAPPED, true)); + }); + }); + } + })); + }); + parent.extendsFrom(remappingConfig); + return remappingConfig; + } +} diff --git a/src/legacy/java/net/neoforged/moddevgradle/legacy/RemapJarTask.java b/src/legacy/java/net/neoforged/moddevgradle/legacy/RemapJarTask.java new file mode 100644 index 00000000..37d51e69 --- /dev/null +++ b/src/legacy/java/net/neoforged/moddevgradle/legacy/RemapJarTask.java @@ -0,0 +1,46 @@ +package net.neoforged.moddevgradle.legacy; + +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.tasks.InputFile; +import org.gradle.api.tasks.InputFiles; +import org.gradle.api.tasks.Nested; +import org.gradle.api.tasks.Optional; +import org.gradle.api.tasks.TaskAction; +import org.gradle.jvm.tasks.Jar; +import org.gradle.process.ExecOperations; + +import javax.inject.Inject; +import java.io.IOException; + +/** + * Task used to remap a jar using AutoRenamingTool. + */ +public abstract class RemapJarTask extends Jar { + + @Nested + protected abstract RemapParameters getParameters(); + + @Inject + public RemapJarTask() { + super(); + } + + /** + * The libraries to use for inheritance data during the renaming process. + */ + @Optional + @InputFiles + public abstract ConfigurableFileCollection getLibraries(); + + @InputFile + public abstract RegularFileProperty getInput(); + + @Inject + protected abstract ExecOperations getExecOperations(); + + @TaskAction + public void remap() throws IOException { + getParameters().execute(getExecOperations(), getInput().getAsFile().get(), getArchiveFile().get().getAsFile(), getLibraries()); + } +} diff --git a/src/legacy/java/net/neoforged/moddevgradle/legacy/RemapParameters.java b/src/legacy/java/net/neoforged/moddevgradle/legacy/RemapParameters.java new file mode 100644 index 00000000..cf030f86 --- /dev/null +++ b/src/legacy/java/net/neoforged/moddevgradle/legacy/RemapParameters.java @@ -0,0 +1,94 @@ +package net.neoforged.moddevgradle.legacy; + +import net.neoforged.moddevgradle.internal.utils.NetworkSettingPassthrough; +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.file.FileCollection; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.provider.Property; +import org.gradle.api.tasks.Classpath; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.InputFiles; +import org.gradle.api.tasks.Internal; +import org.gradle.api.tasks.PathSensitive; +import org.gradle.api.tasks.PathSensitivity; +import org.gradle.process.ExecOperations; + +import javax.inject.Inject; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.io.Serializable; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +abstract class RemapParameters implements Serializable { + @Inject + public RemapParameters() {} + + @Classpath + @InputFiles + protected abstract ConfigurableFileCollection getToolClasspath(); + + @InputFiles + @PathSensitive(PathSensitivity.NONE) + public abstract ConfigurableFileCollection getMappings(); + + @Internal + public abstract RegularFileProperty getLogFile(); + + @Input + public abstract Property getToolType(); + + public void from(Obfuscation reobfuscation, ToolType toolType) { + getToolType().set(toolType); + if (toolType == ToolType.ART) { + getToolClasspath().from(reobfuscation.autoRenamingToolRuntime); + getMappings().from(reobfuscation.officialToSrg); + } else { + getToolClasspath().from(reobfuscation.installerToolsRuntime); + getMappings().from(reobfuscation.mappingsCsv); + } + } + + public void execute(ExecOperations operations, File input, File output, FileCollection libraries) throws IOException { + final List args = new ArrayList<>(); + + args.addAll(Arrays.asList("--input", input.getAbsolutePath())); + args.addAll(Arrays.asList("--output", output.getAbsolutePath())); + if (getToolType().get() == ToolType.ART) { + getMappings().forEach(file -> args.addAll(Arrays.asList("--names", file.getAbsolutePath()))); + libraries.forEach(lib -> args.addAll(Arrays.asList("--lib", lib.getAbsolutePath()))); + args.add("--disable-abstract-param"); + args.add("--strip-sigs"); + } else { + args.addAll(Arrays.asList("--task", "SRG_TO_MCP")); + getMappings().forEach(file -> args.addAll(Arrays.asList("--mcp", file.getAbsolutePath()))); + args.add("--strip-signatures"); + } + + try (var log = getLogFile().isPresent() ? Files.newOutputStream(getLogFile().get().getAsFile().toPath()) : new OutputStream() { + @Override + public void write(int b) { + } + }) { + operations.javaexec(execSpec -> { + // Pass through network properties + execSpec.systemProperties(NetworkSettingPassthrough.getNetworkSystemProperties()); + + // See https://github.com/gradle/gradle/issues/28959 + execSpec.jvmArgs("-Dstdout.encoding=UTF-8", "-Dstderr.encoding=UTF-8"); + + execSpec.classpath(getToolClasspath()); + execSpec.args(args); + execSpec.setStandardOutput(log); + }).rethrowFailure().assertNormalExitValue(); + } + } + + public enum ToolType { + ART, + INSTALLER_TOOLS + } +} diff --git a/src/legacy/java/net/neoforged/moddevgradle/legacy/RemappingTransform.java b/src/legacy/java/net/neoforged/moddevgradle/legacy/RemappingTransform.java new file mode 100644 index 00000000..a962ae2a --- /dev/null +++ b/src/legacy/java/net/neoforged/moddevgradle/legacy/RemappingTransform.java @@ -0,0 +1,65 @@ +package net.neoforged.moddevgradle.legacy; + +import org.gradle.api.artifacts.transform.CacheableTransform; +import org.gradle.api.artifacts.transform.InputArtifact; +import org.gradle.api.artifacts.transform.InputArtifactDependencies; +import org.gradle.api.artifacts.transform.TransformAction; +import org.gradle.api.artifacts.transform.TransformOutputs; +import org.gradle.api.artifacts.transform.TransformParameters; +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.file.FileCollection; +import org.gradle.api.file.FileSystemLocation; +import org.gradle.api.provider.Property; +import org.gradle.api.provider.Provider; +import org.gradle.api.tasks.CompileClasspath; +import org.gradle.api.tasks.InputFiles; +import org.gradle.api.tasks.Nested; +import org.gradle.api.tasks.PathSensitive; +import org.gradle.api.tasks.PathSensitivity; +import org.gradle.process.ExecOperations; + +import javax.inject.Inject; +import java.io.IOException; + +@CacheableTransform +public abstract class RemappingTransform implements TransformAction { + @InputArtifact + @PathSensitive(PathSensitivity.NONE) + public abstract Provider getInputArtifact(); + + @CompileClasspath + @InputArtifactDependencies + public abstract FileCollection getDependencies(); + + @Inject + protected abstract ExecOperations getExecOperations(); + + @Override + public void transform(TransformOutputs outputs) { + var inputFile = getInputArtifact().get().getAsFile(); + // The file may not yet exist if i.e. IntelliJ requests it during indexing + if (!inputFile.exists()) return; + + var mappedFile = outputs.file(inputFile.getName()); + try { + getParameters().getParameters().get() + .execute( + getExecOperations(), + inputFile, + mappedFile, + getDependencies().plus(getParameters().getMinecraftDependencies()) + ); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public interface Parameters extends TransformParameters { + @Nested + Property getParameters(); + + @InputFiles + @PathSensitive(PathSensitivity.NONE) + ConfigurableFileCollection getMinecraftDependencies(); + } +} diff --git a/src/main/java/net/neoforged/moddevgradle/dsl/NeoForgeExtension.java b/src/main/java/net/neoforged/moddevgradle/dsl/NeoForgeExtension.java index 98850d1d..ba0baf06 100644 --- a/src/main/java/net/neoforged/moddevgradle/dsl/NeoForgeExtension.java +++ b/src/main/java/net/neoforged/moddevgradle/dsl/NeoForgeExtension.java @@ -38,6 +38,9 @@ public NeoForgeExtension(Project project, DataFileCollection accessTransformers, runs = project.container(RunModel.class); parchment = project.getObjects().newInstance(Parchment.class); unitTest = project.getObjects().newInstance(UnitTest.class); + getNeoForgeArtifact().convention(getVersion().map(version -> "net.neoforged:neoforge:" + version)); + getNeoFormArtifact().convention(getNeoFormVersion().map(version -> "net.neoforged:neoform:" + version)); + this.accessTransformers = accessTransformers; this.interfaceInjectionData = interfaceInjectionData; getValidateAccessTransformers().convention(false); @@ -62,7 +65,8 @@ public void addModdingDependenciesTo(SourceSet sourceSet) { } /** - * NeoForge version number. You have to set either this or {@link #getNeoFormVersion()}. + * NeoForge version number. You have to set either this, {@link #getNeoFormVersion()} + * or {@link #getNeoFormArtifact()}. */ public abstract Property getVersion(); @@ -70,9 +74,28 @@ public void addModdingDependenciesTo(SourceSet sourceSet) { * You can set this property to a version of NeoForm * to either override the version used in the version of NeoForge you set, or to compile against * Vanilla artifacts that have no NeoForge code added. + *

+ * This property is mutually exclusive with {@link #getNeoFormArtifact()}. */ public abstract Property getNeoFormVersion(); + /** + * Is derived automatically from {@link #getVersion()}. + * + * @return Maven artifact coordinate (group:module:version) + */ + public abstract Property getNeoForgeArtifact(); + + /** + * Derived automatically from the {@link #getNeoFormVersion()}. + * You can override this property to use i.e. MCP for up to 1.20.1. + *

+ * This property is mutually exclusive with {@link #getNeoForgeArtifact()}. + * + * @return Maven artifact coordinate (group:module:version) + */ + public abstract Property getNeoFormArtifact(); + /** * The list of additional access transformers that should be applied to the Minecraft source code. *

diff --git a/src/main/java/net/neoforged/moddevgradle/internal/ModDevPlugin.java b/src/main/java/net/neoforged/moddevgradle/internal/ModDevPlugin.java index 89cb81ad..e2f04cdd 100644 --- a/src/main/java/net/neoforged/moddevgradle/internal/ModDevPlugin.java +++ b/src/main/java/net/neoforged/moddevgradle/internal/ModDevPlugin.java @@ -182,13 +182,13 @@ public void apply(Project project) { // When a NeoForge version is specified, we use the dependencies published by that, and otherwise // we fall back to a potentially specified NeoForm version, which allows us to run in "Vanilla" mode. - var neoForgeModDevLibrariesDependency = extension.getVersion().map(version -> { - return dependencyFactory.create("net.neoforged:neoforge:" + version) + var neoForgeModDevLibrariesDependency = extension.getNeoForgeArtifact().map(artifactId -> { + return dependencyFactory.create(artifactId) .capabilities(caps -> { caps.requireCapability("net.neoforged:neoforge-dependencies"); }); - }).orElse(extension.getNeoFormVersion().map(version -> { - return dependencyFactory.create("net.neoforged:neoform:" + version) + }).orElse(extension.getNeoFormArtifact().map(artifact -> { + return dependencyFactory.create(artifact) .capabilities(caps -> { caps.requireCapability("net.neoforged:neoform-dependencies"); }); @@ -225,13 +225,24 @@ public void apply(Project project) { Function> jarPathFactory = suffix -> { return minecraftArtifactsDir.zip( // It's helpful to be able to differentiate the Vanilla jar and the NeoForge jar in classic multiloader setups. - extension.getVersion().map(v -> "neoforge-" + v).orElse(extension.getNeoFormVersion().map(v -> "vanilla-" + v)), + extension.getNeoForgeArtifact().map(art -> { + var split = art.split(":", 3); + return split[1] + "-" + split[2]; + }) + .orElse(extension.getNeoFormArtifact().map(v -> "vanilla-" + v.split(":", 3)[2])), (dir, prefix) -> dir.file(prefix + "-minecraft" + suffix + ".jar")); }; task.getCompiledArtifact().set(jarPathFactory.apply("")); task.getCompiledWithSourcesArtifact().set(jarPathFactory.apply("-merged")); task.getSourcesArtifact().set(jarPathFactory.apply("-sources")); - task.getResourcesArtifact().set(jarPathFactory.apply("-resources-aka-client-extra")); + task.getResourcesArtifact().set(minecraftArtifactsDir.zip( + extension.getNeoForgeArtifact().map(art -> { + var split = art.split(":", 3); + return split[2] + "-" + split[1]; + }) + .orElse(extension.getNeoFormArtifact().map(v -> "vanilla-" + v.split(":", 3)[2])), + (dir, prefix) -> dir.file("client-extra-aka-minecraft-resources-" + prefix + ".jar") + )); task.getNeoForgeArtifact().set(getNeoForgeUserDevDependencyNotation(extension)); task.getNeoFormArtifact().set(getNeoFormDataDependencyNotation(extension)); @@ -297,8 +308,8 @@ public void apply(Project project) { spec.setCanBeResolved(true); spec.setCanBeConsumed(false); spec.setTransitive(false); - spec.getDependencies().addLater(extension.getVersion().map(version -> { - return dependencyFactory.create("net.neoforged:neoforge:" + version) + spec.getDependencies().addLater(extension.getNeoForgeArtifact().map(artifact -> { + return dependencyFactory.create(artifact) .capabilities(caps -> { caps.requireCapability("net.neoforged:neoforge-moddev-config"); }); @@ -331,8 +342,8 @@ public void apply(Project project) { spec.setCanBeConsumed(false); spec.shouldResolveConsistentlyWith(runtimeClasspathConfig.get()); // NOTE: When running in vanilla mode, this configuration is simply empty - spec.getDependencies().addLater(extension.getVersion().map(version -> { - return dependencyFactory.create("net.neoforged:neoforge:" + version) + spec.getDependencies().addLater(extension.getNeoForgeArtifact().map(artifact -> { + return dependencyFactory.create(artifact) .capabilities(caps -> { caps.requireCapability("net.neoforged:neoforge-moddev-module-path"); }) @@ -391,7 +402,7 @@ public void apply(Project project) { ideSyncTask.configure(task -> task.dependsOn(prepareRunTask)); var createLaunchScriptTask = tasks.register(InternalModelHelper.nameOfRun(run, "create", "launchScript"), CreateLaunchScriptTask.class, task -> { - task.setGroup(INTERNAL_TASK_GROUP); + task.setGroup(TASK_GROUP); task.setDescription("Creates a bash/shell-script to launch the " + run.getName() + " Minecraft run from outside Gradle or your IDE."); task.getWorkingDirectory().set(run.getGameDirectory().map(d -> d.getAsFile().getAbsolutePath())); @@ -415,7 +426,6 @@ public void apply(Project project) { task.getEnvironment().set(run.getEnvironment()); task.getModFolders().set(RunUtils.getGradleModFoldersProvider(project, run.getLoadedMods(), false)); }); - ideSyncTask.configure(task -> task.dependsOn(createLaunchScriptTask)); tasks.register(InternalModelHelper.nameOfRun(run, "run", ""), RunGameTask.class, task -> { task.setGroup(TASK_GROUP); @@ -460,11 +470,11 @@ public void apply(Project project) { } private static Provider getNeoFormDataDependencyNotation(NeoForgeExtension extension) { - return extension.getNeoFormVersion().map(version -> "net.neoforged:neoform:" + version + "@zip"); + return extension.getNeoFormArtifact().map(art -> art + "@zip"); } private static Provider getNeoForgeUserDevDependencyNotation(NeoForgeExtension extension) { - return extension.getVersion().map(version -> "net.neoforged:neoforge:" + version + ":userdev"); + return extension.getNeoForgeArtifact().map(art -> art + ":userdev"); } /** @@ -476,8 +486,8 @@ private List configureArtifactManifestConfigurations(Project proj var configurationPrefix = "neoFormRuntimeDependencies"; - Provider neoForgeDependency = extension.getVersion().map(version -> dependencyFactory.create("net.neoforged:neoforge:" + version)); - Provider neoFormDependency = extension.getNeoFormVersion().map(version -> dependencyFactory.create("net.neoforged:neoform:" + version)); + Provider neoForgeDependency = extension.getNeoForgeArtifact().map(dependencyFactory::create); + Provider neoFormDependency = extension.getNeoFormArtifact().map(dependencyFactory::create); // Gradle prevents us from having dependencies with "incompatible attributes" in the same configuration. // What constitutes incompatible cannot be overridden on a per-configuration basis. @@ -535,7 +545,7 @@ private List configureArtifactManifestConfigurations(Project proj spec.setDescription("Dependencies needed for running NeoFormRuntime for the selected NeoForge/NeoForm version (Classpath)"); spec.setCanBeConsumed(false); spec.setCanBeResolved(true); - spec.getDependencies().addLater(neoForgeDependency); // Universal Jar + spec.getDependencies().addLater(extension.getNeoForgeArtifact().map(a -> a + ":universal").map(dependencyFactory::create)); // Universal Jar spec.getDependencies().addLater(neoForgeDependency.map(dependency -> dependency.copy() .capabilities(caps -> { caps.requireCapability("net.neoforged:neoforge-dependencies"); @@ -548,6 +558,8 @@ private List configureArtifactManifestConfigurations(Project proj spec.attributes(attributes -> { setNamedAttribute(attributes, Usage.USAGE_ATTRIBUTE, Usage.JAVA_RUNTIME); setNamedAttribute(attributes, MinecraftDistribution.ATTRIBUTE, MinecraftDistribution.CLIENT); + setNamedAttribute(attributes, Category.CATEGORY_ATTRIBUTE, project.getObjects().named(Category.class, Category.LIBRARY)); + setNamedAttribute(attributes, LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.getObjects().named(LibraryElements.class, LibraryElements.JAR)); }); }); @@ -613,8 +625,8 @@ private void setupTesting(Project project, spec.setCanBeConsumed(false); spec.shouldResolveConsistentlyWith(testRuntimeClasspathConfig.get()); // NOTE: When running in vanilla mode, this configuration is simply empty - spec.getDependencies().addLater(extension.getVersion().map(version -> { - return dependencyFactory.create("net.neoforged:neoforge:" + version) + spec.getDependencies().addLater(extension.getNeoForgeArtifact().map(art -> { + return dependencyFactory.create(art) .capabilities(caps -> { caps.requireCapability("net.neoforged:neoforge-moddev-module-path"); }) @@ -751,7 +763,7 @@ private static void addIntelliJRunConfiguration(Project project, } appRun.setModuleName(RunUtils.getIntellijModuleName(project, sourceSet)); appRun.setWorkingDirectory(run.getGameDirectory().get().getAsFile().getAbsolutePath()); - appRun.setEnvs(run.getEnvironment().get()); + appRun.setEnvs(RunUtils.replaceModClassesEnv(run, () -> RunUtils.getIdeaModFoldersProvider(project, outputDirectory, run.getMods(), false))); appRun.setJvmArgs( RunUtils.escapeJvmArg(RunUtils.getArgFileParameter(prepareTask.getVmArgsFile().get())) @@ -974,7 +986,7 @@ private static void addEclipseLaunchConfiguration(Project project, RunUtils.escapeJvmArg(RunUtils.getEclipseModFoldersProvider(project, run.getLoadedMods(), false).getArgument()) ) .args(RunUtils.escapeJvmArg(RunUtils.getArgFileParameter(prepareTask.getProgramArgsFile().get()))) - .envVar(run.getEnvironment().get()) + .envVar(RunUtils.replaceModClassesEnv(run, () -> RunUtils.getEclipseModFoldersProvider(project, run.getMods(), false))) .workingDirectory(run.getGameDirectory().get().getAsFile().getAbsolutePath()) .build(RunUtils.DEV_LAUNCH_MAIN_CLASS); RunUtils.writeEclipseLaunchConfig(project, launchConfigName, config); diff --git a/src/main/java/net/neoforged/moddevgradle/internal/RunUtils.java b/src/main/java/net/neoforged/moddevgradle/internal/RunUtils.java index 8dead3cf..f5352784 100644 --- a/src/main/java/net/neoforged/moddevgradle/internal/RunUtils.java +++ b/src/main/java/net/neoforged/moddevgradle/internal/RunUtils.java @@ -15,6 +15,7 @@ import org.gradle.api.file.Directory; import org.gradle.api.file.RegularFile; import org.gradle.api.provider.MapProperty; +import org.gradle.api.provider.Property; import org.gradle.api.provider.Provider; import org.gradle.api.tasks.Classpath; import org.gradle.api.tasks.InputFiles; @@ -41,6 +42,7 @@ import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -48,6 +50,7 @@ import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Function; +import java.util.function.Supplier; import java.util.stream.Collectors; final class RunUtils { @@ -206,7 +209,7 @@ public static String getArgFileParameter(RegularFile argFile) { } public static ModFoldersProvider getGradleModFoldersProvider(Project project, Provider> modsProvider, boolean includeUnitTests) { - var modFoldersProvider = project.getObjects().newInstance(ModFoldersProvider.class); + var modFoldersProvider = project.getObjects().newInstance(ModFoldersProvider.class, project); modFoldersProvider.getModFolders().set(getModFoldersForGradle(project, modsProvider, includeUnitTests)); return modFoldersProvider; } @@ -231,6 +234,16 @@ private static Project findSourceSetProject(Project someProject, SourceSet sourc throw new IllegalArgumentException("Could not find project for source set " + someProject); } + public static Map replaceModClassesEnv(RunModel model, Supplier newProvider) { + var vars = model.getEnvironment().get(); + if (vars.containsKey("MOD_CLASSES")) { + final var copy = new HashMap<>(vars); + copy.put("MOD_CLASSES", newProvider.get().getClassesArgument().get()); + return copy; + } + return vars; + } + public static ModFoldersProvider getIdeaModFoldersProvider(Project project, @Nullable Function outputDirectory, Provider> modsProvider, @@ -245,7 +258,7 @@ public static ModFoldersProvider getIdeaModFoldersProvider(Project project, folders = getModFoldersForGradle(project, modsProvider, includeUnitTests); } - var modFoldersProvider = project.getObjects().newInstance(ModFoldersProvider.class); + var modFoldersProvider = project.getObjects().newInstance(ModFoldersProvider.class, project); modFoldersProvider.getModFolders().set(folders); return modFoldersProvider; } @@ -405,24 +418,29 @@ record AssetProperties(String assetIndex, String assetsRoot) { abstract class ModFoldersProvider implements CommandLineArgumentProvider { @Inject - public ModFoldersProvider() { + public ModFoldersProvider(Project project) { + getClassesArgument().set(project.provider(() -> { + var stringModFolderMap = getModFolders().get(); + return stringModFolderMap.entrySet().stream() + .mapMulti((entry, output) -> { + for (var directory : entry.getValue().getFolders()) { + // Resources + output.accept(entry.getKey() + "%%" + directory.getAbsolutePath()); + } + }) + .collect(Collectors.joining(File.pathSeparator)); + })); } @Nested abstract MapProperty getModFolders(); + @Internal + abstract Property getClassesArgument(); + @Internal public String getArgument() { - var stringModFolderMap = getModFolders().get(); - return "-Dfml.modFolders=%s".formatted( - stringModFolderMap.entrySet().stream() - .mapMulti((entry, output) -> { - for (var directory : entry.getValue().getFolders()) { - // Resources - output.accept(entry.getKey() + "%%" + directory.getAbsolutePath()); - } - }) - .collect(Collectors.joining(File.pathSeparator))); + return "-Dfml.modFolders=%s".formatted(getClassesArgument().get()); } @Override diff --git a/src/main/java/net/neoforged/moddevgradle/internal/UserDevConfig.java b/src/main/java/net/neoforged/moddevgradle/internal/UserDevConfig.java index 364cff3e..04345e30 100644 --- a/src/main/java/net/neoforged/moddevgradle/internal/UserDevConfig.java +++ b/src/main/java/net/neoforged/moddevgradle/internal/UserDevConfig.java @@ -3,15 +3,37 @@ import com.google.gson.Gson; import org.gradle.api.GradleException; +import java.io.BufferedReader; import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; import java.io.Serializable; import java.nio.file.Files; import java.util.List; import java.util.Map; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; public record UserDevConfig(String mcp, String sources, String universal, List libraries, List modules, Map runs) implements Serializable { public static UserDevConfig from(File userDevFile) { + // For backwards compatibility reasons we also support loading this from the userdev jar + if (userDevFile.getName().endsWith(".jar")) { + try (var zf = new ZipFile(userDevFile)) { + var configJson = zf.getEntry("config.json"); + if (configJson != null) { + try (var in = zf.getInputStream(configJson); + var reader = new BufferedReader(new InputStreamReader(in))) { + return new Gson().fromJson(reader, UserDevConfig.class); + } catch (Exception e) { + throw new GradleException("Failed to read NeoForge config file from " + userDevFile, e); + } + } + } catch (IOException e) { + throw new GradleException("Failed to read NeoForge config file from " + userDevFile, e); + } + } + try (var reader = Files.newBufferedReader(userDevFile.toPath())) { return new Gson().fromJson(reader, UserDevConfig.class); } catch (Exception e) { diff --git a/src/main/java/net/neoforged/nfrtgradle/NeoFormRuntimeExtension.java b/src/main/java/net/neoforged/nfrtgradle/NeoFormRuntimeExtension.java index 4ee3f302..e0020640 100644 --- a/src/main/java/net/neoforged/nfrtgradle/NeoFormRuntimeExtension.java +++ b/src/main/java/net/neoforged/nfrtgradle/NeoFormRuntimeExtension.java @@ -13,7 +13,7 @@ public abstract class NeoFormRuntimeExtension { public static final String NAME = "neoFormRuntime"; - private static final String DEFAULT_NFRT_VERSION = "1.0.6"; + private static final String DEFAULT_NFRT_VERSION = "1.0.9"; @Inject public NeoFormRuntimeExtension(Project project) { diff --git a/testproject/gradle/wrapper/gradle-wrapper.jar b/testproject/gradle/wrapper/gradle-wrapper.jar index 2c352119..a4b76b95 100644 Binary files a/testproject/gradle/wrapper/gradle-wrapper.jar and b/testproject/gradle/wrapper/gradle-wrapper.jar differ diff --git a/testproject/gradle/wrapper/gradle-wrapper.properties b/testproject/gradle/wrapper/gradle-wrapper.properties index dedd5d1e..66cd5a0e 100644 --- a/testproject/gradle/wrapper/gradle-wrapper.properties +++ b/testproject/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-all.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/testproject/oldneo/build.gradle b/testproject/oldneo/build.gradle new file mode 100644 index 00000000..73dd3654 --- /dev/null +++ b/testproject/oldneo/build.gradle @@ -0,0 +1,8 @@ + +plugins { + id 'net.neoforged.moddev' +} + +neoForge { + version = "20.4.237" +} diff --git a/testproject/settings.gradle b/testproject/settings.gradle index 952a551e..7b293c2d 100644 --- a/testproject/settings.gradle +++ b/testproject/settings.gradle @@ -21,5 +21,6 @@ include 'subproject' include 'common' include 'jijtest' include 'coremod' +//include 'oldneo' enableFeaturePreview "STABLE_CONFIGURATION_CACHE"