From a706b070f7722e92835e8459785f96eed3d4f0a8 Mon Sep 17 00:00:00 2001 From: Technici4n <13494793+Technici4n@users.noreply.github.com> Date: Thu, 15 Aug 2024 23:34:19 +0200 Subject: [PATCH] Switch to custom neodev plugin based on moddev --- build.gradle | 19 +- buildSrc/build.gradle | 23 + buildSrc/gradle.properties | 3 + buildSrc/settings.gradle | 0 .../neodev/ApplyAccessTransformer.java | 60 ++ .../net/neoforged/neodev/ApplyPatches.java | 74 +++ .../neodev/CreateCleanArtifacts.java | 36 ++ .../neodev/GenerateBinaryPatches.java | 70 +++ .../neodev/GenerateSourcePatches.java | 55 ++ .../neoforged/neodev/NeoDevBasePlugin.java | 23 + .../net/neoforged/neodev/NeoDevExtension.java | 35 ++ .../neoforged/neodev/NeoDevExtraPlugin.java | 95 +++ .../net/neoforged/neodev/NeoDevPlugin.java | 550 ++++++++++++++++++ .../neoforged/neodev/NeoDevTestExtension.java | 30 + .../java/net/neoforged/neodev/RemapJar.java | 44 ++ .../main/java/net/neoforged/neodev/Tools.java | 33 ++ .../neoforged/neodev/WriteUserDevConfig.java | 194 ++++++ .../installer/ArtifactPathsCollector.java | 47 ++ .../neodev/installer/CreateArgsFile.java | 128 ++++ .../installer/CreateInstallerProfile.java | 204 +++++++ .../installer/CreateLauncherProfile.java | 128 ++++ .../neodev/installer/InstallerProcessor.java | 16 + .../neoforged/neodev/installer/Library.java | 5 + .../neodev/installer/LibraryArtifact.java | 7 + .../neodev/installer/LibraryCollector.java | 220 +++++++ .../neodev/installer/LibraryDownload.java | 4 + .../ModuleIdentificationVisitor.java | 51 ++ gradle.properties | 16 +- gradle/wrapper/gradle-wrapper.properties | 2 +- projects/base/build.gradle | 16 +- projects/neoforge/build.gradle | 293 ++++------ settings.gradle | 28 +- testframework/build.gradle | 27 +- tests/build.gradle | 145 +++-- 34 files changed, 2389 insertions(+), 292 deletions(-) create mode 100644 buildSrc/gradle.properties create mode 100644 buildSrc/settings.gradle create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/ApplyAccessTransformer.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/ApplyPatches.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/CreateCleanArtifacts.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/GenerateBinaryPatches.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/GenerateSourcePatches.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/NeoDevBasePlugin.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/NeoDevExtension.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/NeoDevExtraPlugin.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/NeoDevPlugin.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/NeoDevTestExtension.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/RemapJar.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/Tools.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/WriteUserDevConfig.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/installer/ArtifactPathsCollector.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/installer/CreateArgsFile.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/installer/CreateInstallerProfile.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/installer/CreateLauncherProfile.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/installer/InstallerProcessor.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/installer/Library.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryArtifact.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryCollector.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryDownload.java create mode 100644 buildSrc/src/main/java/net/neoforged/neodev/installer/ModuleIdentificationVisitor.java diff --git a/build.gradle b/build.gradle index 6c46fb5ba61..fbc90b7d61c 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ import java.util.regex.Pattern plugins { id 'net.neoforged.gradleutils' version '3.0.0' id 'com.diffplug.spotless' version '6.22.0' apply false - id 'net.neoforged.licenser' version '0.7.2' + id 'net.neoforged.licenser' version '0.7.5' id 'neoforge.formatting-conventions' id 'neoforge.versioning' } @@ -23,19 +23,22 @@ System.out.println("NeoForge version ${project.version}") allprojects { version rootProject.version group 'net.neoforged' - repositories { - mavenLocal() - } -} -subprojects { apply plugin: 'java' java.toolchain.languageVersion.set(JavaLanguageVersion.of(project.java_version)) } -repositories { - mavenCentral() +// Remove src/ sources from the root project. They are used in the neoforge subproject. +sourceSets { + main { + java { + srcDirs = [] + } + resources { + srcDirs = [] + } + } } // Put licenser here otherwise it tries to license all source sets including decompiled MC sources diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index 67840524598..e89269c0edc 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -1,3 +1,26 @@ plugins { + id 'java-gradle-plugin' id 'groovy-gradle-plugin' } + +repositories { + gradlePluginPortal() + mavenCentral() + maven { + name = "NeoForged" + url = "https://maven.neoforged.net/releases" + content { + includeGroup "codechicken" + includeGroup "net.neoforged" + } + } +} + +dependencies { + // buildSrc is an includedbuild of the parent directory (gradle.parent) + // ../settings.gradle sets the moddevgradle_plugin_version accordingly + implementation "net.neoforged:moddev-gradle:${gradle.parent.ext.moddevgradle_plugin_version}" + + implementation "com.google.code.gson:gson:${project.gson_version}" + implementation "io.codechicken:DiffPatch:${project.diffpatch_version}" +} diff --git a/buildSrc/gradle.properties b/buildSrc/gradle.properties new file mode 100644 index 00000000000..6665e0d8775 --- /dev/null +++ b/buildSrc/gradle.properties @@ -0,0 +1,3 @@ + +gson_version=2.11.0 +diffpatch_version=2.0.0.35 diff --git a/buildSrc/settings.gradle b/buildSrc/settings.gradle new file mode 100644 index 00000000000..e69de29bb2d diff --git a/buildSrc/src/main/java/net/neoforged/neodev/ApplyAccessTransformer.java b/buildSrc/src/main/java/net/neoforged/neodev/ApplyAccessTransformer.java new file mode 100644 index 00000000000..b208523caff --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/ApplyAccessTransformer.java @@ -0,0 +1,60 @@ +package net.neoforged.neodev; + +import net.neoforged.moddevgradle.internal.utils.FileUtils; +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.tasks.Classpath; +import org.gradle.api.tasks.InputFile; +import org.gradle.api.tasks.Internal; +import org.gradle.api.tasks.JavaExec; +import org.gradle.api.tasks.OutputFile; +import org.gradle.api.tasks.TaskAction; + +import javax.inject.Inject; +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; + +abstract class ApplyAccessTransformer extends JavaExec { + @InputFile + public abstract RegularFileProperty getInputJar(); + + @InputFile + public abstract RegularFileProperty getAccessTransformer(); + + @OutputFile + public abstract RegularFileProperty getOutputJar(); + + // Used to give JST more information about the classes. + @Classpath + public abstract ConfigurableFileCollection getLibraries(); + + @Internal + public abstract RegularFileProperty getLibrariesFile(); + + @Inject + public ApplyAccessTransformer() {} + + @Override + @TaskAction + public void exec() { + try { + FileUtils.writeLinesSafe( + getLibrariesFile().getAsFile().get().toPath(), + getLibraries().getFiles().stream().map(File::getAbsolutePath).toList(), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new UncheckedIOException("Failed to write libraries for JST.", exception); + } + + args( + "--enable-accesstransformers", + "--access-transformer", getAccessTransformer().getAsFile().get().getAbsolutePath(), + "--libraries-list", getLibrariesFile().getAsFile().get().getAbsolutePath(), + getInputJar().getAsFile().get().getAbsolutePath(), + getOutputJar().getAsFile().get().getAbsolutePath()); + + super.exec(); + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/ApplyPatches.java b/buildSrc/src/main/java/net/neoforged/neodev/ApplyPatches.java new file mode 100644 index 00000000000..58ed2fc31bc --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/ApplyPatches.java @@ -0,0 +1,74 @@ +package net.neoforged.neodev; + +import io.codechicken.diffpatch.cli.PatchOperation; +import io.codechicken.diffpatch.util.Input.MultiInput; +import io.codechicken.diffpatch.util.Output.MultiOutput; +import io.codechicken.diffpatch.util.PatchMode; +import org.gradle.api.DefaultTask; +import org.gradle.api.Project; +import org.gradle.api.file.DirectoryProperty; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.provider.Property; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.InputDirectory; +import org.gradle.api.tasks.InputFile; +import org.gradle.api.tasks.OutputDirectory; +import org.gradle.api.tasks.OutputFile; +import org.gradle.api.tasks.PathSensitive; +import org.gradle.api.tasks.PathSensitivity; +import org.gradle.api.tasks.TaskAction; +import org.gradle.work.DisableCachingByDefault; + +import javax.inject.Inject; +import java.io.IOException; + +@DisableCachingByDefault(because = "Not worth caching") +abstract class ApplyPatches extends DefaultTask { + @InputFile + public abstract RegularFileProperty getOriginalJar(); + + @InputDirectory + @PathSensitive(PathSensitivity.NONE) + public abstract DirectoryProperty getPatchesFolder(); + + @OutputFile + public abstract RegularFileProperty getPatchedJar(); + + @OutputDirectory + public abstract DirectoryProperty getRejectsFolder(); + + @Input + protected abstract Property getIsUpdating(); + + @Inject + public ApplyPatches(Project project) { + getIsUpdating().set(project.getProviders().gradleProperty("updating").map(Boolean::parseBoolean).orElse(false)); + } + + @TaskAction + public void applyPatches() throws IOException { + var isUpdating = getIsUpdating().get(); + + var builder = PatchOperation.builder() + .logTo(getLogger()::lifecycle) + .baseInput(MultiInput.detectedArchive(getOriginalJar().get().getAsFile().toPath())) + .patchesInput(MultiInput.folder(getPatchesFolder().get().getAsFile().toPath())) + .patchedOutput(MultiOutput.detectedArchive(getPatchedJar().get().getAsFile().toPath())) + .rejectsOutput(MultiOutput.folder(getRejectsFolder().get().getAsFile().toPath())) + .mode(isUpdating ? PatchMode.FUZZY : PatchMode.ACCESS) + .aPrefix("a/") + .bPrefix("b/") + .level(isUpdating ? io.codechicken.diffpatch.util.LogLevel.ALL : io.codechicken.diffpatch.util.LogLevel.WARN) + .minFuzz(0.9f); // The 0.5 default in DiffPatch is too low. + + var result = builder.build().operate(); + + int exit = result.exit; + if (exit != 0 && exit != 1) { + throw new RuntimeException("DiffPatch failed with exit code: " + exit); + } + if (exit != 0 && !isUpdating) { + throw new RuntimeException("Patches failed to apply."); + } + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/CreateCleanArtifacts.java b/buildSrc/src/main/java/net/neoforged/neodev/CreateCleanArtifacts.java new file mode 100644 index 00000000000..2cb2e89ade2 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/CreateCleanArtifacts.java @@ -0,0 +1,36 @@ +package net.neoforged.neodev; + +import net.neoforged.nfrtgradle.CreateMinecraftArtifacts; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.tasks.OutputFile; + +import javax.inject.Inject; + +abstract class CreateCleanArtifacts extends CreateMinecraftArtifacts { + @OutputFile + abstract RegularFileProperty getCleanClientJar(); + + @OutputFile + abstract RegularFileProperty getRawServerJar(); + + @OutputFile + abstract RegularFileProperty getCleanServerJar(); + + @OutputFile + abstract RegularFileProperty getCleanJoinedJar(); + + @OutputFile + abstract RegularFileProperty getMergedMappings(); + + @Inject + public CreateCleanArtifacts() { + getAdditionalResults().put("node.stripClient.output.output", getCleanClientJar().getAsFile()); + getAdditionalResults().put("node.downloadServer.output.output", getRawServerJar().getAsFile()); + getAdditionalResults().put("node.stripServer.output.output", getCleanServerJar().getAsFile()); + getAdditionalResults().put("node.rename.output.output", getCleanJoinedJar().getAsFile()); + getAdditionalResults().put("node.mergeMappings.output.output", getMergedMappings().getAsFile()); + + // TODO: does anyone care about this? they should be contained in the client mappings + //"--write-result", "node.downloadServerMappings.output.output:" + getServerMappings().get().getAsFile().getAbsolutePath() + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/GenerateBinaryPatches.java b/buildSrc/src/main/java/net/neoforged/neodev/GenerateBinaryPatches.java new file mode 100644 index 00000000000..35a06a8c33f --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/GenerateBinaryPatches.java @@ -0,0 +1,70 @@ +package net.neoforged.neodev; + +import org.gradle.api.GradleException; +import org.gradle.api.file.DirectoryProperty; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.tasks.InputDirectory; +import org.gradle.api.tasks.InputFile; +import org.gradle.api.tasks.JavaExec; +import org.gradle.api.tasks.Optional; +import org.gradle.api.tasks.OutputFile; + +import javax.inject.Inject; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +abstract class GenerateBinaryPatches extends JavaExec { + @Inject + public GenerateBinaryPatches() {} + + /** + * The jar file containing classes in the base state. + */ + @InputFile + abstract RegularFileProperty getCleanJar(); + + /** + * The jar file containing classes in the desired target state. + */ + @InputFile + abstract RegularFileProperty getPatchedJar(); + + @InputFile + abstract RegularFileProperty getMappings(); + + /** + * This directory of patch files for the Java sources is used as a hint to only diff class files that + * supposedly have changed. If it is not set, the tool will diff every .class file instead. + */ + @InputDirectory + @Optional + abstract DirectoryProperty getSourcePatchesFolder(); + + /** + * The location where the LZMA compressed binary patches are written to. + */ + @OutputFile + abstract RegularFileProperty getOutputFile(); + + @Override + public void exec() { + args("--clean", getCleanJar().get().getAsFile().getAbsolutePath()); + args("--dirty", getPatchedJar().get().getAsFile().getAbsolutePath()); + args("--srg", getMappings().get().getAsFile().getAbsolutePath()); + if (getSourcePatchesFolder().isPresent()) { + args("--patches", getSourcePatchesFolder().get().getAsFile().getAbsolutePath()); + } + args("--output", getOutputFile().get().getAsFile().getAbsolutePath()); + + var logFile = new File(getTemporaryDir(), "console.log"); + try (var out = new BufferedOutputStream(new FileOutputStream(logFile))) { + getLogger().info("Logging binpatcher console output to {}", logFile.getAbsolutePath()); + setStandardOutput(out); + super.exec(); + } catch (IOException e) { + throw new GradleException("Failed to create binary patches.", e); + } + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/GenerateSourcePatches.java b/buildSrc/src/main/java/net/neoforged/neodev/GenerateSourcePatches.java new file mode 100644 index 00000000000..c6e1c7e7302 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/GenerateSourcePatches.java @@ -0,0 +1,55 @@ +package net.neoforged.neodev; + +import io.codechicken.diffpatch.cli.CliOperation; +import io.codechicken.diffpatch.cli.DiffOperation; +import io.codechicken.diffpatch.util.Input.MultiInput; +import io.codechicken.diffpatch.util.Output.MultiOutput; +import org.gradle.api.DefaultTask; +import org.gradle.api.file.DirectoryProperty; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.tasks.InputDirectory; +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.TaskAction; + +import javax.inject.Inject; +import java.io.IOException; + +abstract class GenerateSourcePatches extends DefaultTask { + @InputFile + public abstract RegularFileProperty getOriginalJar(); + + @InputDirectory + @PathSensitive(PathSensitivity.RELATIVE) + public abstract DirectoryProperty getModifiedSources(); + + @OutputFile + public abstract RegularFileProperty getPatchesJar(); + + @Inject + public GenerateSourcePatches() {} + + @TaskAction + public void generateSourcePatches() throws IOException { + var builder = DiffOperation.builder() + .logTo(getLogger()::lifecycle) + .baseInput(MultiInput.detectedArchive(getOriginalJar().get().getAsFile().toPath())) + .changedInput(MultiInput.folder(getModifiedSources().get().getAsFile().toPath())) + .patchesOutput(MultiOutput.detectedArchive(getPatchesJar().get().getAsFile().toPath())) + .autoHeader(true) + .level(io.codechicken.diffpatch.util.LogLevel.WARN) + .summary(false) + .aPrefix("a/") + .bPrefix("b/") + .lineEnding("\n"); + + CliOperation.Result result = builder.build().operate(); + + int exit = result.exit; + if (exit != 0 && exit != 1) { + throw new RuntimeException("DiffPatch failed with exit code: " + exit); + } + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/NeoDevBasePlugin.java b/buildSrc/src/main/java/net/neoforged/neodev/NeoDevBasePlugin.java new file mode 100644 index 00000000000..9a5c382b4b0 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/NeoDevBasePlugin.java @@ -0,0 +1,23 @@ +package net.neoforged.neodev; + +import net.neoforged.minecraftdependencies.MinecraftDependenciesPlugin; +import net.neoforged.nfrtgradle.CreateMinecraftArtifacts; +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.api.tasks.Sync; + +public class NeoDevBasePlugin implements Plugin { + @Override + public void apply(Project project) { + // These plugins allow us to declare dependencies on Minecraft libraries needed to compile the official sources + project.getPlugins().apply(MinecraftDependenciesPlugin.class); + + var createSources = NeoDevPlugin.configureMinecraftDecompilation(project); + + project.getTasks().register("setup", Sync.class, task -> { + task.setDescription("Replaces the contents of the base project sources with the unpatched, decompiled Minecraft source code."); + task.from(project.zipTree(createSources.flatMap(CreateMinecraftArtifacts::getSourcesArtifact))); + task.into(project.file("src/main/java/")); + }); + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/NeoDevExtension.java b/buildSrc/src/main/java/net/neoforged/neodev/NeoDevExtension.java new file mode 100644 index 00000000000..224c7ab7e99 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/NeoDevExtension.java @@ -0,0 +1,35 @@ +package net.neoforged.neodev; + +import net.neoforged.moddevgradle.dsl.ModModel; +import net.neoforged.moddevgradle.dsl.RunModel; +import org.gradle.api.Action; +import org.gradle.api.NamedDomainObjectContainer; +import org.gradle.api.Project; + +public class NeoDevExtension { + public static final String NAME = "neoDev"; + + private final NamedDomainObjectContainer mods; + private final NamedDomainObjectContainer runs; + + public NeoDevExtension(Project project) { + mods = project.container(ModModel.class); + runs = project.container(RunModel.class, name -> project.getObjects().newInstance(RunModel.class, name, project, mods)); + } + + public NamedDomainObjectContainer getMods() { + return mods; + } + + public void mods(Action> action) { + action.execute(mods); + } + + public NamedDomainObjectContainer getRuns() { + return runs; + } + + public void runs(Action> action) { + action.execute(runs); + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/NeoDevExtraPlugin.java b/buildSrc/src/main/java/net/neoforged/neodev/NeoDevExtraPlugin.java new file mode 100644 index 00000000000..fabb8f75acb --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/NeoDevExtraPlugin.java @@ -0,0 +1,95 @@ +package net.neoforged.neodev; + +import net.neoforged.minecraftdependencies.MinecraftDependenciesPlugin; +import net.neoforged.moddevgradle.internal.NeoDevFacade; +import net.neoforged.nfrtgradle.CreateMinecraftArtifacts; +import net.neoforged.nfrtgradle.DownloadAssets; +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.api.artifacts.Configuration; +import org.gradle.api.artifacts.ProjectDependency; +import org.gradle.api.artifacts.dsl.DependencyFactory; +import org.gradle.api.tasks.testing.Test; + +import java.util.function.Consumer; + +// TODO: the only point of this is to configure runs that depend on neoforge. Maybe this could be done with less code duplication... +// TODO: Gradle says "thou shalt not referenceth otherth projects" yet here we are +// TODO: depend on neoforge configurations that the moddev plugin also uses +public class NeoDevExtraPlugin implements Plugin { + @Override + public void apply(Project project) { + project.getPlugins().apply(MinecraftDependenciesPlugin.class); + + var neoForgeProject = project.getRootProject().getChildProjects().get("neoforge"); + + var dependencyFactory = project.getDependencyFactory(); + var tasks = project.getTasks(); + var neoDevBuildDir = project.getLayout().getBuildDirectory().dir("neodev"); + + var extension = project.getExtensions().create(NeoDevExtension.NAME, NeoDevExtension.class); + + var rawNeoFormVersion = project.getProviders().gradleProperty("neoform_version"); + var minecraftVersion = project.getProviders().gradleProperty("minecraft_version"); + var mcAndNeoFormVersion = minecraftVersion.zip(rawNeoFormVersion, (mc, nf) -> mc + "-" + nf); + + // TODO: this is temporary + var modulesConfiguration = project.getConfigurations().create("moduleOnly", spec -> { + spec.getDependencies().add(projectDep(dependencyFactory, neoForgeProject, "moduleOnly")); + }); + + var downloadAssets = neoForgeProject.getTasks().named("downloadAssets", DownloadAssets.class); + var createArtifacts = neoForgeProject.getTasks().named("createSourceArtifacts", CreateMinecraftArtifacts.class); + var writeNeoDevConfig = neoForgeProject.getTasks().named("writeNeoDevConfig", WriteUserDevConfig.class); + + Consumer configureLegacyClasspath = spec -> { + spec.getDependencies().addLater(mcAndNeoFormVersion.map(v -> dependencyFactory.create("net.neoforged:neoform:" + v).capabilities(caps -> { + caps.requireCapability("net.neoforged:neoform-dependencies"); + }))); + spec.getDependencies().add(projectDep(dependencyFactory, neoForgeProject, "installer")); + spec.getDependencies().add(projectDep(dependencyFactory, neoForgeProject, "moduleOnly")); + spec.getDependencies().add(projectDep(dependencyFactory, neoForgeProject, "userdevCompileOnly")); + // TODO: Convert into a cross-project dependency too + spec.getDependencies().add( + dependencyFactory.create( + project.files(createArtifacts.flatMap(CreateMinecraftArtifacts::getResourcesArtifact)) + ) + ); + }; + + extension.getRuns().configureEach(run -> { + configureLegacyClasspath.accept(run.getAdditionalRuntimeClasspathConfiguration()); + }); + NeoDevFacade.setupRuns( + project, + neoDevBuildDir, + extension.getRuns(), + writeNeoDevConfig, + modulePath -> modulePath.extendsFrom(modulesConfiguration), + configureLegacyClasspath, + downloadAssets.flatMap(DownloadAssets::getAssetPropertiesFile) + ); + + var testExtension = project.getExtensions().create(NeoDevTestExtension.NAME, NeoDevTestExtension.class); + var testTask = tasks.register("junitTest", Test.class, test -> test.setGroup("verification")); + tasks.named("check").configure(task -> task.dependsOn(testTask)); + + NeoDevFacade.setupTestTask( + project, + neoDevBuildDir, + testTask, + writeNeoDevConfig, + testExtension.getLoadedMods(), + testExtension.getTestedMod(), + modulePath -> modulePath.extendsFrom(modulesConfiguration), + configureLegacyClasspath, + downloadAssets.flatMap(DownloadAssets::getAssetPropertiesFile) + ); + } + + private static ProjectDependency projectDep(DependencyFactory dependencyFactory, Project project, String configurationName) { + var dep = dependencyFactory.create(project); + dep.setTargetConfiguration(configurationName); + return dep; + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/NeoDevPlugin.java b/buildSrc/src/main/java/net/neoforged/neodev/NeoDevPlugin.java new file mode 100644 index 00000000000..36f720a2d36 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/NeoDevPlugin.java @@ -0,0 +1,550 @@ +package net.neoforged.neodev; + +import net.neoforged.minecraftdependencies.MinecraftDependenciesPlugin; +import net.neoforged.moddevgradle.internal.NeoDevFacade; +import net.neoforged.moddevgradle.internal.utils.DependencyUtils; +import net.neoforged.moddevgradle.tasks.JarJar; +import net.neoforged.neodev.installer.CreateArgsFile; +import net.neoforged.neodev.installer.CreateInstallerProfile; +import net.neoforged.neodev.installer.CreateLauncherProfile; +import net.neoforged.neodev.installer.InstallerProcessor; +import net.neoforged.nfrtgradle.CreateMinecraftArtifacts; +import net.neoforged.nfrtgradle.DownloadAssets; +import net.neoforged.nfrtgradle.NeoFormRuntimePlugin; +import net.neoforged.nfrtgradle.NeoFormRuntimeTask; +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.api.artifacts.Configuration; +import org.gradle.api.artifacts.repositories.MavenArtifactRepository; +import org.gradle.api.file.Directory; +import org.gradle.api.file.RegularFile; +import org.gradle.api.plugins.BasePluginExtension; +import org.gradle.api.plugins.JavaPlugin; +import org.gradle.api.plugins.JavaPluginExtension; +import org.gradle.api.provider.Provider; +import org.gradle.api.tasks.Sync; +import org.gradle.api.tasks.TaskProvider; +import org.gradle.api.tasks.bundling.AbstractArchiveTask; +import org.gradle.api.tasks.bundling.Jar; +import org.gradle.api.tasks.bundling.Zip; + +import java.io.File; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class NeoDevPlugin implements Plugin { + @Override + public void apply(Project project) { + project.getPlugins().apply(MinecraftDependenciesPlugin.class); + + var createSourceArtifacts = configureMinecraftDecompilation(project); + + var configurations = project.getConfigurations(); + var runtimeClasspath = configurations.getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME); + var dependencyFactory = project.getDependencyFactory(); + var tasks = project.getTasks(); + var neoDevBuildDir = project.getLayout().getBuildDirectory().dir("neodev"); + + var rawNeoFormVersion = project.getProviders().gradleProperty("neoform_version"); + var fmlVersion = project.getProviders().gradleProperty("fancy_mod_loader_version"); + var minecraftVersion = project.getProviders().gradleProperty("minecraft_version"); + var neoForgeVersion = project.provider(() -> (String) project.getVersion()); // TODO: is this correct? + var mcAndNeoFormVersion = minecraftVersion.zip(rawNeoFormVersion, (mc, nf) -> mc + "-" + nf); + + var extension = project.getExtensions().create(NeoDevExtension.NAME, NeoDevExtension.class); + + var neoFormDependencies = configurations.create("neoFormDependencies", spec -> { + spec.setCanBeConsumed(false); + spec.setCanBeResolved(true); + spec.getDependencies().addLater(mcAndNeoFormVersion.map(version -> { + var dep = dependencyFactory.create("net.neoforged:neoform:" + version).capabilities(caps -> { + caps.requireCapability("net.neoforged:neoform-dependencies"); + }); + dep.endorseStrictVersions(); + return dep; + })); + }); + + var jstConfiguration = configurations.create("javaSourceTransformer", files -> { + files.setCanBeConsumed(false); + files.setCanBeResolved(true); + files.defaultDependencies(spec -> { + spec.add(Tools.JST.asDependency(project)); + }); + }); + + var atFile = project.getRootProject().file("src/main/resources/META-INF/accesstransformer.cfg"); + var applyAt = tasks.register("applyAccessTransformer", ApplyAccessTransformer.class, task -> { + task.classpath(jstConfiguration); + task.getInputJar().set(createSourceArtifacts.flatMap(CreateMinecraftArtifacts::getSourcesArtifact)); + task.getAccessTransformer().set(atFile); + task.getOutputJar().set(neoDevBuildDir.map(dir -> dir.file("artifacts/access-transformed-sources.jar"))); + task.getLibraries().from(neoFormDependencies); + task.getLibrariesFile().set(neoDevBuildDir.map(dir -> dir.file("minecraft-libraries-for-jst.txt"))); + }); + + var patchesFolder = project.getRootProject().file("patches"); + var applyPatches = tasks.register("applyPatches", ApplyPatches.class, task -> { + task.getOriginalJar().set(applyAt.flatMap(ApplyAccessTransformer::getOutputJar)); + task.getPatchesFolder().set(patchesFolder); + task.getPatchedJar().set(neoDevBuildDir.map(dir -> dir.file("artifacts/patched-sources.jar"))); + task.getRejectsFolder().set(project.getRootProject().file("rejects")); + }); + + var mcSourcesPath = project.file("src/main/java"); + tasks.register("setup", Sync.class, task -> { + task.from(project.zipTree(applyPatches.flatMap(ApplyPatches::getPatchedJar))); + task.into(mcSourcesPath); + }); + + var downloadAssets = tasks.register("downloadAssets", DownloadAssets.class, task -> { + task.getNeoFormArtifact().set(mcAndNeoFormVersion.map(v -> "net.neoforged:neoform:" + v + "@zip")); + task.getAssetPropertiesFile().set(neoDevBuildDir.map(dir -> dir.file("minecraft_assets.properties"))); + }); + + var installerConfiguration = project.getConfigurations().create("installer"); + var installerLibrariesConfiguration = configurations.create("installerLibraries"); + var modulesConfiguration = configurations.create("moduleOnly"); + var userDevCompileOnlyConfiguration = configurations.create("userdevCompileOnly"); + var userDevTestImplementationConfiguration = configurations.create("userdevTestImplementation"); + userDevTestImplementationConfiguration.shouldResolveConsistentlyWith(runtimeClasspath); + + var devLibrariesConfiguration = configurations.create("devLibraries", files -> { + files.setCanBeConsumed(false); + files.setCanBeResolved(true); + }); + devLibrariesConfiguration.shouldResolveConsistentlyWith(runtimeClasspath); + devLibrariesConfiguration.extendsFrom(installerLibrariesConfiguration, modulesConfiguration, userDevCompileOnlyConfiguration); + + var writeNeoDevConfig = tasks.register("writeNeoDevConfig", WriteUserDevConfig.class, task -> { + task.getForNeoDev().set(true); + task.getUserDevConfig().set(neoDevBuildDir.map(dir -> dir.file("neodev-config.json"))); + }); + var writeUserDevConfig = tasks.register("writeUserDevConfig", WriteUserDevConfig.class, task -> { + task.getForNeoDev().set(false); + task.getUserDevConfig().set(neoDevBuildDir.map(dir -> dir.file("userdev-config.json"))); + }); + for (var taskProvider : List.of(writeNeoDevConfig, writeUserDevConfig)) { + taskProvider.configure(task -> { + task.getFmlVersion().set(fmlVersion); + task.getMinecraftVersion().set(minecraftVersion); + task.getNeoForgeVersion().set(neoForgeVersion); + task.getRawNeoFormVersion().set(rawNeoFormVersion); + task.getLibraries().addAll(configurationToGavList(devLibrariesConfiguration)); + task.getModules().addAll(configurationToGavList(modulesConfiguration)); + task.getTestLibraries().addAll(configurationToGavList(userDevTestImplementationConfiguration)); + task.getTestLibraries().add(neoForgeVersion.map(v -> "net.neoforged:testframework:" + v)); + task.getIgnoreList().addAll(modulesConfiguration.getIncoming().getArtifacts().getResolvedArtifacts().map(results -> { + return results.stream().map(r -> r.getFile().getName()).toList(); + })); + task.getIgnoreList().addAll(userDevCompileOnlyConfiguration.getIncoming().getArtifacts().getResolvedArtifacts().map(results -> { + return results.stream().map(r -> r.getFile().getName()).toList(); + })); + task.getIgnoreList().addAll("client-extra", "neoforge-"); + task.getBinpatcherGav().set(Tools.BINPATCHER.asGav(project)); + }); + } + + NeoDevFacade.setupRuns( + project, + neoDevBuildDir, + extension.getRuns(), + writeNeoDevConfig, + modulePath -> { + modulePath.extendsFrom(modulesConfiguration); + }, + legacyClassPath -> { + legacyClassPath.getDependencies().addLater(mcAndNeoFormVersion.map(v -> dependencyFactory.create("net.neoforged:neoform:" + v).capabilities(caps -> { + caps.requireCapability("net.neoforged:neoform-dependencies"); + }))); + legacyClassPath.getDependencies().add( + dependencyFactory.create( + project.files(createSourceArtifacts.flatMap(CreateMinecraftArtifacts::getResourcesArtifact)) + ) + ); + legacyClassPath.extendsFrom(installerLibrariesConfiguration, modulesConfiguration, userDevCompileOnlyConfiguration); + }, + downloadAssets.flatMap(DownloadAssets::getAssetPropertiesFile) + ); + + var genSourcePatches = tasks.register("generateSourcePatches", GenerateSourcePatches.class, task -> { + task.getOriginalJar().set(applyAt.flatMap(ApplyAccessTransformer::getOutputJar)); + task.getModifiedSources().set(project.file("src/main/java")); + task.getPatchesJar().set(neoDevBuildDir.map(dir -> dir.file("source-patches.zip"))); + }); + + var genPatches = tasks.register("genPatches", Sync.class, task -> { + task.from(project.zipTree(genSourcePatches.flatMap(GenerateSourcePatches::getPatchesJar))); + task.into(project.getRootProject().file("patches")); + }); + + // TODO: signing? + var universalJar = tasks.register("universalJar", Jar.class, task -> { + task.getArchiveClassifier().set("universal"); + + task.from(project.zipTree( + tasks.named("jar", Jar.class).flatMap(AbstractArchiveTask::getArchiveFile))); + task.exclude("net/minecraft/**"); + task.exclude("com/**"); + task.exclude("mcp/**"); + + task.manifest(manifest -> { + manifest.attributes(Map.of("FML-System-Mods", "neoforge")); + manifest.attributes( + Map.of( + "Specification-Title", "NeoForge", + "Specification-Vendor", "NeoForge", + "Specification-Version", project.getVersion().toString().substring(0, project.getVersion().toString().lastIndexOf(".")), + "Implementation-Title", project.getGroup(), + "Implementation-Version", project.getVersion(), + "Implementation-Vendor", "NeoForged"), + "net/neoforged/neoforge/internal/versions/neoforge/"); + manifest.attributes( + Map.of( + "Specification-Title", "Minecraft", + "Specification-Vendor", "Mojang", + "Specification-Version", minecraftVersion, + "Implementation-Title", "MCP", + "Implementation-Version", mcAndNeoFormVersion, + "Implementation-Vendor", "NeoForged"), + "net/neoforged/neoforge/versions/neoform/"); + }); + }); + + var jarJarTask = JarJar.registerWithConfiguration(project, "jarJar"); + universalJar.configure(task -> task.from(jarJarTask)); + + var createCleanArtifacts = tasks.register("createCleanArtifacts", CreateCleanArtifacts.class, task -> { + var cleanArtifactsDir = neoDevBuildDir.map(dir -> dir.dir("artifacts/clean")); + task.getCleanClientJar().set(cleanArtifactsDir.map(dir -> dir.file("client.jar"))); + task.getRawServerJar().set(cleanArtifactsDir.map(dir -> dir.file("raw-server.jar"))); + task.getCleanServerJar().set(cleanArtifactsDir.map(dir -> dir.file("server.jar"))); + task.getCleanJoinedJar().set(cleanArtifactsDir.map(dir -> dir.file("joined.jar"))); + task.getMergedMappings().set(cleanArtifactsDir.map(dir -> dir.file("merged-mappings.txt"))); + task.getNeoFormArtifact().set(mcAndNeoFormVersion.map(version -> "net.neoforged:neoform:" + version + "@zip")); + }); + + var binaryPatchOutputs = configureBinaryPatchCreation( + project, + createCleanArtifacts, + neoDevBuildDir, + patchesFolder + ); + + var createLauncherProfile = tasks.register("createLauncherProfile", CreateLauncherProfile.class, task -> { + task.getFmlVersion().set(fmlVersion); + task.getMinecraftVersion().set(minecraftVersion); + task.getNeoForgeVersion().set(neoForgeVersion); + task.getRawNeoFormVersion().set(rawNeoFormVersion); + task.getLibraries().from(installerConfiguration, modulesConfiguration); + task.getRepositoryURLs().set(project.provider(() -> { + List repos = new ArrayList<>(); + for (var repo : project.getRepositories().withType(MavenArtifactRepository.class)) { + var uri = repo.getUrl(); + if (!uri.toString().endsWith("/")) { + uri = URI.create(uri + "/"); + } + repos.add(uri); + } + return repos; + })); + task.getIgnoreList().addAll(modulesConfiguration.getIncoming().getArtifacts().getResolvedArtifacts().map(results -> { + return results.stream().map(r -> r.getFile().getName()).toList(); + })); + task.getIgnoreList().addAll("client-extra", "neoforge-"); + task.getModulePath().from(modulesConfiguration); + task.getLauncherProfile().set(neoDevBuildDir.map(dir -> dir.file("launcher-profile.json"))); + }); + + var installerProfileLibraries = configurations.create("installerProfileLibraries", spec -> { + spec.setCanBeResolved(true); + spec.setCanBeConsumed(false); + }); + installerProfileLibraries.extendsFrom(installerLibrariesConfiguration); + installerProfileLibraries.shouldResolveConsistentlyWith(runtimeClasspath); + var createInstallerProfile = tasks.register("createInstallerProfile", CreateInstallerProfile.class, task -> { + task.getMinecraftVersion().set(minecraftVersion); + task.getNeoForgeVersion().set(neoForgeVersion); + task.getMcAndNeoFormVersion().set(mcAndNeoFormVersion); + task.getIcon().set(project.getRootProject().file("docs/assets/neoforged.ico")); + task.getLibraries().from(installerProfileLibraries); + task.getRepositoryURLs().set(project.provider(() -> { + List repos = new ArrayList<>(); + for (var repo : project.getRepositories().withType(MavenArtifactRepository.class)) { + var uri = repo.getUrl(); + if (!uri.toString().endsWith("/")) { + uri = URI.create(uri + "/"); + } + repos.add(uri); + } + return repos; + })); + task.getUniversalJar().set(universalJar.flatMap(AbstractArchiveTask::getArchiveFile)); + task.getInstallerProfile().set(neoDevBuildDir.map(dir -> dir.file("installer-profile.json"))); + }); + + for (var installerProcessor : InstallerProcessor.values()) { + var configuration = configurations.create("installerProcessor" + installerProcessor.toString(), files -> { + files.setCanBeConsumed(false); + files.setCanBeResolved(true); + files.getDependencies().add(installerProcessor.tool.asDependency(project)); + }); + installerProfileLibraries.extendsFrom(configuration); + // Each tool should resolve consistently with the full set of installed libraries. + configuration.shouldResolveConsistentlyWith(installerProfileLibraries); + createInstallerProfile.configure(task -> { + task.getProcessorClasspaths().put(installerProcessor, configuration.getIncoming().getArtifacts().getResolvedArtifacts().map(results -> { + // Using .toList() fails with the configuration cache - looks like Gradle can't deserialize the resulting list? + return results.stream().map(DependencyUtils::guessMavenGav).collect(Collectors.toCollection(ArrayList::new)); + })); + task.getProcessorGavs().put(installerProcessor, installerProcessor.tool.asGav(project)); + }); + } + + var createWindowsServerArgsFile = tasks.register("createWindowsServerArgsFile", CreateArgsFile.class, task -> { + task.getPathSeparator().set(";"); + task.getArgsFile().set(neoDevBuildDir.map(dir -> dir.file("windows-server-args.txt"))); + }); + var createUnixServerArgsFile = tasks.register("createUnixServerArgsFile", CreateArgsFile.class, task -> { + task.getPathSeparator().set(":"); + task.getArgsFile().set(neoDevBuildDir.map(dir -> dir.file("unix-server-args.txt"))); + }); + + for (var taskProvider : List.of(createWindowsServerArgsFile, createUnixServerArgsFile)) { + taskProvider.configure(task -> { + task.getTemplate().set(project.getRootProject().file("server_files/args.txt")); + task.getFmlVersion().set(fmlVersion); + task.getMinecraftVersion().set(minecraftVersion); + task.getNeoForgeVersion().set(neoForgeVersion); + task.getRawNeoFormVersion().set(rawNeoFormVersion); + task.getModules().from(modulesConfiguration); + task.getIgnoreList().addAll(modulesConfiguration.getIncoming().getArtifacts().getResolvedArtifacts().map(results -> { + return results.stream().map(r -> r.getFile().getName()).toList(); + })); + task.getClasspath().from(installerConfiguration); + task.getRawServerJar().set(createCleanArtifacts.flatMap(CreateCleanArtifacts::getRawServerJar)); + }); + } + + var installerConfig = configurations.create("legacyInstaller", files -> { + files.setCanBeConsumed(false); + files.setCanBeResolved(true); + files.setTransitive(false); + files.getDependencies().add(Tools.LEGACYINSTALLER.asDependency(project)); + }); + // TODO: signing? + // We want to use the manifest from LegacyInstaller. + // - Jar tasks have special manifest handling, so use Zip. + // - The manifest must be the first entry in the jar so LegacyInstaller has to be the first input. + var installerJar = tasks.register("installerJar", Zip.class, task -> { + task.getArchiveClassifier().set("installer"); + task.getArchiveExtension().set("jar"); + task.setMetadataCharset("UTF-8"); + task.getDestinationDirectory().convention(project.getExtensions().getByType(BasePluginExtension.class).getLibsDirectory()); + + // TODO: is this correct? + task.from(project.zipTree(project.provider(installerConfig::getSingleFile)), spec -> { + spec.exclude("big_logo.png"); + }); + task.from(createLauncherProfile.flatMap(CreateLauncherProfile::getLauncherProfile), spec -> { + spec.rename(s -> "version.json"); + }); + task.from(createInstallerProfile.flatMap(CreateInstallerProfile::getInstallerProfile), spec -> { + spec.rename(s -> "install_profile.json"); + }); + task.from(project.getRootProject().file("src/main/resources/url.png")); + task.from(project.getRootProject().file("src/main/resources/neoforged_logo.png"), spec -> { + spec.rename(s -> "big_logo.png"); + }); + task.from(createUnixServerArgsFile.flatMap(CreateArgsFile::getArgsFile), spec -> { + spec.into("data"); + spec.rename(s -> "unix_args.txt"); + }); + task.from(createWindowsServerArgsFile.flatMap(CreateArgsFile::getArgsFile), spec -> { + spec.into("data"); + spec.rename(s -> "win_args.txt"); + }); + task.from(binaryPatchOutputs.binaryPatchesForClient(), spec -> { + spec.into("data"); + spec.rename(s -> "client.lzma"); + }); + task.from(binaryPatchOutputs.binaryPatchesForServer(), spec -> { + spec.into("data"); + spec.rename(s -> "server.lzma"); + }); + var mavenPath = neoForgeVersion.map(v -> "net/neoforged/neoforge/" + v); + task.getInputs().property("mavenPath", mavenPath); + task.from(project.getRootProject().files("server_files"), spec -> { + spec.into("data"); + spec.exclude("args.txt"); + spec.filter(s -> { + return s.replaceAll("@MAVEN_PATH@", mavenPath.get()); + }); + }); + + // This is true by default (see gradle.properties), and needs to be disabled explicitly when building (see release.yml). + if (project.getProperties().containsKey("neogradle.runtime.platform.installer.debug") && Boolean.parseBoolean(project.getProperties().get("neogradle.runtime.platform.installer.debug").toString())) { + task.from(universalJar.flatMap(AbstractArchiveTask::getArchiveFile), spec -> { + spec.into(String.format("/maven/net/neoforged/neoforge/%s/", neoForgeVersion.get())); + spec.rename(name -> String.format("neoforge-%s-universal.jar", neoForgeVersion.get())); + }); + } + }); + + var userdevJar = tasks.register("userdevJar", Jar.class, task -> { + task.getArchiveClassifier().set("userdev"); + + task.from(writeUserDevConfig.flatMap(WriteUserDevConfig::getUserDevConfig), spec -> { + spec.rename(s -> "config.json"); + }); + task.from(atFile, spec -> { + spec.into("ats/"); + }); + task.from(binaryPatchOutputs.binaryPatchesForMerged(), spec -> { + spec.rename(s -> "joined.lzma"); + }); + task.from(project.zipTree(genSourcePatches.flatMap(GenerateSourcePatches::getPatchesJar)), spec -> { + spec.into("patches/"); + }); + }); + + project.getExtensions().getByType(JavaPluginExtension.class).withSourcesJar(); + final TaskProvider sourcesJarProvider = project.getTasks().named("sourcesJar", Jar.class); + sourcesJarProvider.configure(task -> { + task.exclude("net/minecraft/**"); + task.exclude("com/**"); + task.exclude("mcp/**"); + }); + + tasks.named("assemble", task -> { + task.dependsOn(installerJar); + task.dependsOn(universalJar); + task.dependsOn(userdevJar); + task.dependsOn(sourcesJarProvider); + }); + } + + private static BinaryPatchOutputs configureBinaryPatchCreation(Project project, + TaskProvider createCleanArtifacts, + Provider neoDevBuildDir, + File sourcesPatchesFolder) { + var configurations = project.getConfigurations(); + var tasks = project.getTasks(); + + var artConfig = configurations.create("art", spec -> { + spec.setDescription("Used to resolve the jar remapping tool"); + spec.setCanBeConsumed(false); + spec.setCanBeResolved(true); + spec.getDependencies().add(Tools.AUTO_RENAMING_TOOL.asDependency(project)); + }); + var remapClientJar = tasks.register("remapClientJar", RemapJar.class, task -> { + task.setDescription("Creates a Minecraft client jar with the official mappings applied. Used as the base for generating binary patches for the client."); + task.classpath(artConfig); + task.getMainClass().set("net.neoforged.art.Main"); + task.getObfSlimJar().set(createCleanArtifacts.flatMap(CreateCleanArtifacts::getCleanClientJar)); + task.getMergedMappings().set(createCleanArtifacts.flatMap(CreateCleanArtifacts::getMergedMappings)); + task.getMojmapJar().set(neoDevBuildDir.map(dir -> dir.file("remapped-client.jar"))); + }); + var remapServerJar = tasks.register("remapServerJar", RemapJar.class, task -> { + task.setDescription("Creates a Minecraft dedicated server jar with the official mappings applied. Used as the base for generating binary patches for the client."); + task.classpath(artConfig); + task.getMainClass().set("net.neoforged.art.Main"); + task.getObfSlimJar().set(createCleanArtifacts.flatMap(CreateCleanArtifacts::getCleanServerJar)); + task.getMergedMappings().set(createCleanArtifacts.flatMap(CreateCleanArtifacts::getMergedMappings)); + task.getMojmapJar().set(neoDevBuildDir.map(dir -> dir.file("remapped-server.jar"))); + }); + + var binpatcherConfig = configurations.create("binpatcher", spec -> { + spec.setDescription("Used to resolve the tool for creating binary patches"); + spec.setCanBeConsumed(false); + spec.setCanBeResolved(true); + spec.setTransitive(false); + spec.getDependencies().add(Tools.BINPATCHER.asDependency(project)); + }); + var generateMergedBinPatches = tasks.register("generateMergedBinPatches", GenerateBinaryPatches.class, task -> { + task.setDescription("Creates binary patch files by diffing a merged client/server jar-file and the compiled Minecraft classes in this project."); + task.classpath(binpatcherConfig); + task.getCleanJar().set(createCleanArtifacts.flatMap(CreateCleanArtifacts::getCleanJoinedJar)); + task.getPatchedJar().set(tasks.named("jar", Jar.class).flatMap(Jar::getArchiveFile)); + task.getSourcePatchesFolder().set(sourcesPatchesFolder); + task.getMappings().set(createCleanArtifacts.flatMap(CreateCleanArtifacts::getMergedMappings)); + task.getOutputFile().set(neoDevBuildDir.map(dir -> dir.file("merged-binpatches.lzma"))); + }); + var generateClientBinPatches = tasks.register("generateClientBinPatches", GenerateBinaryPatches.class, task -> { + task.setDescription("Creates binary patch files by diffing a merged client jar-file and the compiled Minecraft classes in this project."); + task.classpath(binpatcherConfig); + task.getCleanJar().set(remapClientJar.flatMap(RemapJar::getMojmapJar)); + task.getPatchedJar().set(tasks.named("jar", Jar.class).flatMap(Jar::getArchiveFile)); + task.getSourcePatchesFolder().set(sourcesPatchesFolder); + task.getMappings().set(createCleanArtifacts.flatMap(CreateCleanArtifacts::getMergedMappings)); + task.getOutputFile().set(neoDevBuildDir.map(dir -> dir.file("client-binpatches.lzma"))); + }); + var generateServerBinPatches = tasks.register("generateServerBinPatches", GenerateBinaryPatches.class, task -> { + task.setDescription("Creates binary patch files by diffing a merged server jar-file and the compiled Minecraft classes in this project."); + task.classpath(binpatcherConfig); + task.getCleanJar().set(remapServerJar.flatMap(RemapJar::getMojmapJar)); + task.getPatchedJar().set(tasks.named("jar", Jar.class).flatMap(Jar::getArchiveFile)); + task.getSourcePatchesFolder().set(sourcesPatchesFolder); + task.getMappings().set(createCleanArtifacts.flatMap(CreateCleanArtifacts::getMergedMappings)); + task.getOutputFile().set(neoDevBuildDir.map(dir -> dir.file("server-binpatches.lzma"))); + }); + + return new BinaryPatchOutputs( + generateMergedBinPatches.flatMap(GenerateBinaryPatches::getOutputFile), + generateClientBinPatches.flatMap(GenerateBinaryPatches::getOutputFile), + generateServerBinPatches.flatMap(GenerateBinaryPatches::getOutputFile) + ); + } + + private record BinaryPatchOutputs( + Provider binaryPatchesForMerged, + Provider binaryPatchesForClient, + Provider binaryPatchesForServer + ) { + } + + /** + * Sets up NFRT, and creates the sources and resources artifacts. + */ + static TaskProvider configureMinecraftDecompilation(Project project) { + project.getPlugins().apply(NeoFormRuntimePlugin.class); + + var configurations = project.getConfigurations(); + var dependencyFactory = project.getDependencyFactory(); + var tasks = project.getTasks(); + var neoDevBuildDir = project.getLayout().getBuildDirectory().dir("neodev"); + + var rawNeoFormVersion = project.getProviders().gradleProperty("neoform_version"); + var minecraftVersion = project.getProviders().gradleProperty("minecraft_version"); + var mcAndNeoFormVersion = minecraftVersion.zip(rawNeoFormVersion, (mc, nf) -> mc + "-" + nf); + + // Configuration for all artifacts that should be passed to NFRT to prevent repeated downloads + var neoFormRuntimeArtifactManifestNeoForm = configurations.create("neoFormRuntimeArtifactManifestNeoForm", spec -> { + spec.setCanBeConsumed(false); + spec.setCanBeResolved(true); + spec.getDependencies().addLater(mcAndNeoFormVersion.map(version -> { + return dependencyFactory.create("net.neoforged:neoform:" + version); + })); + }); + + tasks.withType(NeoFormRuntimeTask.class, task -> { + task.addArtifactsToManifest(neoFormRuntimeArtifactManifestNeoForm); + }); + + return tasks.register("createSourceArtifacts", CreateMinecraftArtifacts.class, task -> { + var minecraftArtifactsDir = neoDevBuildDir.map(dir -> dir.dir("artifacts")); + task.getSourcesArtifact().set(minecraftArtifactsDir.map(dir -> dir.file("base-sources.jar"))); + task.getResourcesArtifact().set(minecraftArtifactsDir.map(dir -> dir.file("minecraft-local-resources-aka-client-extra.jar"))); + task.getNeoFormArtifact().set(mcAndNeoFormVersion.map(version -> "net.neoforged:neoform:" + version + "@zip")); + }); + } + + private Provider> configurationToGavList(Configuration configuration) { + return configuration.getIncoming().getArtifacts().getResolvedArtifacts().map(results -> { + return results.stream().map(DependencyUtils::guessMavenGav).toList(); + }); + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/NeoDevTestExtension.java b/buildSrc/src/main/java/net/neoforged/neodev/NeoDevTestExtension.java new file mode 100644 index 00000000000..57d3f7be339 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/NeoDevTestExtension.java @@ -0,0 +1,30 @@ +package net.neoforged.neodev; + +import net.neoforged.moddevgradle.dsl.ModModel; +import org.gradle.api.provider.Property; +import org.gradle.api.provider.SetProperty; + +import javax.inject.Inject; + +public abstract class NeoDevTestExtension { + public static final String NAME = "neoDevTest"; + + @Inject + public NeoDevTestExtension() { + } + + /** + * The mod that will be loaded in JUnit tests. + * The compiled classes from {@code src/test/java} and the resources from {@code src/test/resources} + * will be added to that mod at runtime. + */ + public abstract Property getTestedMod(); + + /** + * The mods to load when running unit tests. Defaults to all mods registered in the project. + * This must contain {@link #getTestedMod()}. + * + * @see ModModel + */ + public abstract SetProperty getLoadedMods(); +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/RemapJar.java b/buildSrc/src/main/java/net/neoforged/neodev/RemapJar.java new file mode 100644 index 00000000000..d9f3d943be3 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/RemapJar.java @@ -0,0 +1,44 @@ +package net.neoforged.neodev; + +import org.gradle.api.GradleException; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.tasks.InputFile; +import org.gradle.api.tasks.JavaExec; +import org.gradle.api.tasks.OutputFile; + +import javax.inject.Inject; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +abstract class RemapJar extends JavaExec { + @Inject + public RemapJar() {} + + @InputFile + abstract RegularFileProperty getObfSlimJar(); + + @InputFile + abstract RegularFileProperty getMergedMappings(); + + @OutputFile + abstract RegularFileProperty getMojmapJar(); + + @Override + public void exec() { + args("--input", getObfSlimJar().get().getAsFile().getAbsolutePath()); + args("--output", getMojmapJar().get().getAsFile().getAbsolutePath()); + args("--names", getMergedMappings().get().getAsFile().getAbsolutePath()); + args("--ann-fix", "--ids-fix", "--src-fix", "--record-fix"); + + var logFile = new File(getTemporaryDir(), "console.log"); + try (var out = new BufferedOutputStream(new FileOutputStream(logFile))) { + getLogger().info("Logging ART console output to {}", logFile.getAbsolutePath()); + setStandardOutput(out); + super.exec(); + } catch (IOException e) { + throw new GradleException("Failed to create binary patches.", e); + } + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/Tools.java b/buildSrc/src/main/java/net/neoforged/neodev/Tools.java new file mode 100644 index 00000000000..8a4ad2d2e77 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/Tools.java @@ -0,0 +1,33 @@ +package net.neoforged.neodev; + +import org.gradle.api.Project; +import org.gradle.api.artifacts.Dependency; + +public enum Tools { + JST("net.neoforged.jst:jst-cli-bundle:%s", "jst_version"), + LEGACYINSTALLER("net.neoforged:legacyinstaller:%s:shrunk", "legacyinstaller_version"), + AUTO_RENAMING_TOOL("net.neoforged:AutoRenamingTool:%s:all", "art_version"), + INSTALLERTOOLS("net.neoforged.installertools:installertools:%s", "installertools_version"), + JARSPLITTER("net.neoforged.installertools:jarsplitter:%s", "installertools_version"), + BINPATCHER("net.neoforged.installertools:binarypatcher:%s:fatjar", "installertools_version"); + + private final String gavPattern; + private final String versionProperty; + + Tools(String gavPattern, String versionProperty) { + this.gavPattern = gavPattern; + this.versionProperty = versionProperty; + } + + public String asGav(Project project) { + var version = project.property(versionProperty); + if (version == null) { + throw new IllegalStateException("Could not find property " + versionProperty); + } + return gavPattern.formatted(version); + } + + public Dependency asDependency(Project project) { + return project.getDependencyFactory().create(asGav(project)); + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/WriteUserDevConfig.java b/buildSrc/src/main/java/net/neoforged/neodev/WriteUserDevConfig.java new file mode 100644 index 00000000000..25bc50b283e --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/WriteUserDevConfig.java @@ -0,0 +1,194 @@ +package net.neoforged.neodev; + +import com.google.gson.GsonBuilder; +import net.neoforged.moddevgradle.internal.utils.FileUtils; +import org.gradle.api.DefaultTask; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.provider.ListProperty; +import org.gradle.api.provider.Property; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.OutputFile; +import org.gradle.api.tasks.TaskAction; + +import javax.inject.Inject; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +abstract class WriteUserDevConfig extends DefaultTask { + @Inject + public WriteUserDevConfig() {} + + @Input + abstract Property getForNeoDev(); + + @Input + abstract Property getFmlVersion(); + + @Input + abstract Property getMinecraftVersion(); + + @Input + abstract Property getNeoForgeVersion(); + + @Input + abstract Property getRawNeoFormVersion(); + + @Input + abstract ListProperty getLibraries(); + + @Input + abstract ListProperty getModules(); + + @Input + abstract ListProperty getTestLibraries(); + + @Input + abstract ListProperty getIgnoreList(); + + @Input + abstract Property getBinpatcherGav(); + + @OutputFile + abstract RegularFileProperty getUserDevConfig(); + + @TaskAction + public void writeUserDevConfig() throws IOException { + var config = new UserDevConfig( + 2, + "net.neoforged:neoform:%s-%s@zip".formatted(getMinecraftVersion().get(), getRawNeoFormVersion().get()), + "ats/", + "joined.lzma", + new BinpatcherConfig( + getBinpatcherGav().get(), + List.of("--clean", "{clean}", "--output", "{output}", "--apply", "{patch}")), + "patches/", + "net.neoforged:neoforge:%s:sources".formatted(getNeoForgeVersion().get()), + "net.neoforged:neoforge:%s:universal".formatted(getNeoForgeVersion().get()), + getLibraries().get(), + getTestLibraries().get(), + new LinkedHashMap<>(), + getModules().get()); + + for (var runType : RunType.values()) { + var launchTarget = switch (runType) { + case CLIENT -> "forgeclient"; + case DATA -> "forgedata"; + case GAME_TEST_SERVER, SERVER -> "forgeserver"; + case JUNIT -> "forgejunit"; + } + (getForNeoDev().get() ? "dev" : "userdev"); + + List args = new ArrayList<>(); + Collections.addAll(args, + "--launchTarget", launchTarget); + + if (runType == RunType.CLIENT || runType == RunType.JUNIT) { + // TODO: this is copied from NG but shouldn't it be the MC version? + Collections.addAll(args, + "--version", getNeoForgeVersion().get()); + } + + if (runType == RunType.CLIENT || runType == RunType.DATA || runType == RunType.JUNIT) { + Collections.addAll(args, + "--assetIndex", "{asset_index}", + "--assetsDir", "{assets_root}"); + } + + Collections.addAll(args, + "--gameDir", ".", + "--fml.fmlVersion", getFmlVersion().get(), + "--fml.mcVersion", getMinecraftVersion().get(), + "--fml.neoForgeVersion", getNeoForgeVersion().get(), + "--fml.neoFormVersion", getRawNeoFormVersion().get()); + + Map systemProperties = new LinkedHashMap<>(); + systemProperties.put("java.net.preferIPv6Addresses", "system"); + systemProperties.put("ignoreList", String.join(",", getIgnoreList().get())); + systemProperties.put("legacyClassPath.file", "{minecraft_classpath_file}"); + + if (runType == RunType.CLIENT || runType == RunType.GAME_TEST_SERVER) { + systemProperties.put("neoforge.enableGameTest", "true"); + + if (runType == RunType.GAME_TEST_SERVER) { + systemProperties.put("neoforge.gameTestServer", "true"); + } + } + + config.runs().put(runType.jsonName, new UserDevRunType( + runType != RunType.JUNIT, + "cpw.mods.bootstraplauncher.BootstrapLauncher", + args, + List.of( + "-p", "{modules}", + "--add-modules", "ALL-MODULE-PATH", + "--add-opens", "java.base/java.util.jar=cpw.mods.securejarhandler", + "--add-opens", "java.base/java.lang.invoke=cpw.mods.securejarhandler", + "--add-exports", "java.base/sun.security.util=cpw.mods.securejarhandler", + "--add-exports", "jdk.naming.dns/com.sun.jndi.dns=java.naming"), + runType == RunType.CLIENT || runType == RunType.JUNIT, + runType == RunType.GAME_TEST_SERVER || runType == RunType.SERVER, + runType == RunType.DATA, + runType == RunType.CLIENT || runType == RunType.GAME_TEST_SERVER, + runType == RunType.JUNIT, + Map.of( + "MOD_CLASSES", "{source_roots}"), + systemProperties + )); + } + + FileUtils.writeStringSafe( + getUserDevConfig().getAsFile().get().toPath(), + new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(config), + // TODO: Not sure what this should be? Most likely the file is ASCII. + StandardCharsets.UTF_8); + } + + private enum RunType { + CLIENT("client"), + DATA("data"), + GAME_TEST_SERVER("gameTestServer"), + SERVER("server"), + JUNIT("junit"); + + private final String jsonName; + + RunType(String jsonName) { + this.jsonName = jsonName; + } + } +} + +record UserDevConfig( + int spec, + String mcp, + String ats, + String binpatches, + BinpatcherConfig binpatcher, + String patches, + String sources, + String universal, + List libraries, + List testLibraries, + Map runs, + List modules) {} + +record BinpatcherConfig( + String version, + List args) {} + +record UserDevRunType( + boolean singleInstance, + String main, + List args, + List jvmArgs, + boolean client, + boolean server, + boolean dataGenerator, + boolean gameTest, + boolean unitTest, + Map env, + Map props) {} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/installer/ArtifactPathsCollector.java b/buildSrc/src/main/java/net/neoforged/neodev/installer/ArtifactPathsCollector.java new file mode 100644 index 00000000000..59aa0b69a8e --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/installer/ArtifactPathsCollector.java @@ -0,0 +1,47 @@ +package net.neoforged.neodev.installer; + +import java.io.File; + +class ArtifactPathsCollector extends ModuleIdentificationVisitor { + + private final StringBuilder builder = new StringBuilder(); + private final String separator; + private final String prefix; + + public ArtifactPathsCollector(String separator, String prefix) { + this.separator = separator; + this.prefix = prefix; + } + + @Override + protected void visitModule(File file, String group, String module, String version, String classifier, final String extension) throws Exception { + builder.append(prefix); + builder.append(group.replace(".", "/")); + builder.append("/"); + builder.append(module); + builder.append("/"); + builder.append(version); + builder.append("/"); + builder.append(module); + builder.append("-"); + builder.append(version); + + if (classifier != null && !classifier.isEmpty()) { + builder.append("-"); + builder.append(classifier); + } + + builder.append(".").append(extension); + builder.append(separator); + } + + @Override + public String toString() { + String result = builder.toString(); + if (result.endsWith(separator)) { + return result.substring(0, result.length() - separator.length()); + } else { + return result; + } + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/installer/CreateArgsFile.java b/buildSrc/src/main/java/net/neoforged/neodev/installer/CreateArgsFile.java new file mode 100644 index 00000000000..159484286c2 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/installer/CreateArgsFile.java @@ -0,0 +1,128 @@ +package net.neoforged.neodev.installer; + +import org.gradle.api.DefaultTask; +import org.gradle.api.file.ArchiveOperations; +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.provider.ListProperty; +import org.gradle.api.provider.Property; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.InputFile; +import org.gradle.api.tasks.InputFiles; +import org.gradle.api.tasks.OutputFile; +import org.gradle.api.tasks.PathSensitive; +import org.gradle.api.tasks.PathSensitivity; +import org.gradle.api.tasks.TaskAction; + +import javax.inject.Inject; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public abstract class CreateArgsFile extends DefaultTask { + @Inject + public CreateArgsFile() {} + + @InputFile + public abstract RegularFileProperty getTemplate(); + + @Input + public abstract Property getFmlVersion(); + + @Input + public abstract Property getMinecraftVersion(); + + @Input + public abstract Property getNeoForgeVersion(); + + @Input + public abstract Property getRawNeoFormVersion(); + + @Input + public abstract Property getPathSeparator(); + + @InputFiles + @PathSensitive(PathSensitivity.NONE) + public abstract ConfigurableFileCollection getModules(); + + @Input + public abstract ListProperty getIgnoreList(); + + @InputFiles + @PathSensitive(PathSensitivity.NONE) + public abstract ConfigurableFileCollection getClasspath(); + + @InputFile + public abstract RegularFileProperty getRawServerJar(); + + @OutputFile + public abstract RegularFileProperty getArgsFile(); + + @Inject + protected abstract ArchiveOperations getArchiveOperations(); + + private String resolveClasspath() throws IOException { + ArtifactPathsCollector classpathCollector = new ArtifactPathsCollector(getPathSeparator().get(), "libraries/"); + getClasspath().getAsFileTree().visit(classpathCollector); + + var ourClasspath = classpathCollector + getPathSeparator().get() + + "libraries/net/minecraft/server/%s/server-%s-extra.jar".formatted( + getRawNeoFormVersion().get(), getRawNeoFormVersion().get()); + + // The raw server jar also contains its own classpath. + // We want to make sure that our versions of the libraries are used when there is a conflict. + var ourClasspathEntries = Stream.of(ourClasspath.split(getPathSeparator().get())) + .map(CreateArgsFile::stripVersionSuffix) + .collect(Collectors.toSet()); + + var serverClasspath = getArchiveOperations().zipTree(getRawServerJar()) + .filter(spec -> spec.getPath().endsWith("META-INF" + File.separator + "classpath-joined")) + .getSingleFile(); + + var filteredServerClasspath = Stream.of(Files.readString(serverClasspath.toPath()).split(";")) + .filter(path -> !ourClasspathEntries.contains(stripVersionSuffix(path))) + // Exclude the actual MC server jar, which is under versions/ + .filter(path -> path.startsWith("libraries/")) + .collect(Collectors.joining(getPathSeparator().get())); + + return ourClasspath + getPathSeparator().get() + filteredServerClasspath; + } + + // Example: + // Convert "libraries/com/github/oshi/oshi-core/6.4.10/oshi-core-6.4.10.jar" + // to "libraries/com/github/oshi/oshi-core". + private static String stripVersionSuffix(String classpathEntry) { + var parts = classpathEntry.split("/"); + return String.join("/", List.of(parts).subList(0, parts.length - 2)); + } + + @TaskAction + public void createArgsFile() throws IOException { + ArtifactPathsCollector modulePathCollector = new ArtifactPathsCollector(getPathSeparator().get(), "libraries/"); + + getModules().getAsFileTree().visit(modulePathCollector); + + var replacements = new HashMap(); + replacements.put("@MODULE_PATH@", modulePathCollector.toString()); + replacements.put("@MODULES@", "ALL-MODULE-PATH"); + replacements.put("@IGNORE_LIST@", String.join(",", getIgnoreList().get())); + replacements.put("@PLUGIN_LAYER_LIBRARIES@", ""); + replacements.put("@GAME_LAYER_LIBRARIES@", ""); + replacements.put("@CLASS_PATH@", resolveClasspath()); + replacements.put("@TASK@", "forgeserver"); + replacements.put("@FORGE_VERSION@", getNeoForgeVersion().get()); + replacements.put("@FML_VERSION@", getFmlVersion().get()); + replacements.put("@MC_VERSION@", getMinecraftVersion().get()); + replacements.put("@MCP_VERSION@", getRawNeoFormVersion().get()); + + var contents = Files.readString(getTemplate().get().getAsFile().toPath()); + for (var entry : replacements.entrySet()) { + contents = contents.replaceAll(entry.getKey(), entry.getValue()); + } + Files.writeString(getArgsFile().get().getAsFile().toPath(), contents); + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/installer/CreateInstallerProfile.java b/buildSrc/src/main/java/net/neoforged/neodev/installer/CreateInstallerProfile.java new file mode 100644 index 00000000000..c72884654bc --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/installer/CreateInstallerProfile.java @@ -0,0 +1,204 @@ +package net.neoforged.neodev.installer; + +import com.google.gson.GsonBuilder; +import net.neoforged.moddevgradle.internal.utils.FileUtils; +import org.gradle.api.DefaultTask; +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.provider.ListProperty; +import org.gradle.api.provider.MapProperty; +import org.gradle.api.provider.Property; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.InputFile; +import org.gradle.api.tasks.InputFiles; +import org.gradle.api.tasks.OutputFile; +import org.gradle.api.tasks.PathSensitive; +import org.gradle.api.tasks.PathSensitivity; +import org.gradle.api.tasks.TaskAction; +import org.jetbrains.annotations.Nullable; + +import javax.inject.Inject; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; + +public abstract class CreateInstallerProfile extends DefaultTask { + @Inject + public CreateInstallerProfile() {} + + @Input + public abstract Property getMinecraftVersion(); + + @Input + public abstract Property getNeoForgeVersion(); + + @Input + public abstract Property getMcAndNeoFormVersion(); + + @InputFile + public abstract RegularFileProperty getIcon(); + + @InputFiles + @PathSensitive(PathSensitivity.NONE) + public abstract ConfigurableFileCollection getLibraries(); + + @Input + public abstract ListProperty getRepositoryURLs(); + + @Input + public abstract MapProperty> getProcessorClasspaths(); + + @Input + public abstract MapProperty getProcessorGavs(); + + @InputFile + public abstract RegularFileProperty getUniversalJar(); + + @OutputFile + public abstract RegularFileProperty getInstallerProfile(); + + private void addProcessor(List processors, @Nullable List sides, InstallerProcessor processor, List args) { + processors.add(new ProcessorEntry(sides, getProcessorGavs().get().get(processor), getProcessorClasspaths().get().get(processor), args)); + } + + @TaskAction + public void createInstallerProfile() throws IOException { + var icon = "data:image/png;base64," + Base64.getEncoder().encodeToString(Files.readAllBytes(getIcon().getAsFile().get().toPath())); + + var data = new LinkedHashMap(); + var neoFormVersion = getMcAndNeoFormVersion().get(); + data.put("MAPPINGS", new LauncherDataEntry(String.format("[net.neoforged:neoform:%s:mappings@txt]", neoFormVersion), String.format("[net.neoforged:neoform:%s:mappings@txt]", neoFormVersion))); + data.put("MOJMAPS", new LauncherDataEntry(String.format("[net.minecraft:client:%s:mappings@txt]", neoFormVersion), String.format("[net.minecraft:server:%s:mappings@txt]", neoFormVersion))); + data.put("MERGED_MAPPINGS", new LauncherDataEntry(String.format("[net.neoforged:neoform:%s:mappings-merged@txt]", neoFormVersion), String.format("[net.neoforged:neoform:%s:mappings-merged@txt]", neoFormVersion))); + data.put("BINPATCH", new LauncherDataEntry("/data/client.lzma", "/data/server.lzma")); + data.put("MC_UNPACKED", new LauncherDataEntry(String.format("[net.minecraft:client:%s:unpacked]", neoFormVersion), String.format("[net.minecraft:server:%s:unpacked]", neoFormVersion))); + data.put("MC_SLIM", new LauncherDataEntry(String.format("[net.minecraft:client:%s:slim]", neoFormVersion), String.format("[net.minecraft:server:%s:slim]", neoFormVersion))); + data.put("MC_EXTRA", new LauncherDataEntry(String.format("[net.minecraft:client:%s:extra]", neoFormVersion), String.format("[net.minecraft:server:%s:extra]", neoFormVersion))); + data.put("MC_SRG", new LauncherDataEntry(String.format("[net.minecraft:client:%s:srg]", neoFormVersion), String.format("[net.minecraft:server:%s:srg]", neoFormVersion))); + data.put("PATCHED", new LauncherDataEntry(String.format("[%s:%s:%s:client]", "net.neoforged", "neoforge", getNeoForgeVersion().get()), String.format("[%s:%s:%s:server]", "net.neoforged", "neoforge", getNeoForgeVersion().get()))); + data.put("MCP_VERSION", new LauncherDataEntry(String.format("'%s'", neoFormVersion), String.format("'%s'", neoFormVersion))); + + var processors = new ArrayList(); + BiConsumer> commonProcessor = (processor, args) -> addProcessor(processors, null, processor, args); + BiConsumer> clientProcessor = (processor, args) -> addProcessor(processors, List.of("client"), processor, args); + BiConsumer> serverProcessor = (processor, args) -> addProcessor(processors, List.of("server"), processor, args); + + serverProcessor.accept(InstallerProcessor.INSTALLERTOOLS, + List.of("--task", "EXTRACT_FILES", "--archive", "{INSTALLER}", + + "--from", "data/run.sh", "--to", "{ROOT}/run.sh", "--exec", "{ROOT}/run.sh", + + "--from", "data/run.bat", "--to", "{ROOT}/run.bat", + + "--from", "data/user_jvm_args.txt", "--to", "{ROOT}/user_jvm_args.txt", "--optional", "{ROOT}/user_jvm_args.txt", + + "--from", "data/win_args.txt", "--to", "{ROOT}/libraries/net/neoforged/neoforge/%s/win_args.txt".formatted(getNeoForgeVersion().get()), + + "--from", "data/unix_args.txt", "--to", "{ROOT}/libraries/net/neoforged/neoforge/%s/unix_args.txt".formatted(getNeoForgeVersion().get())) + ); + serverProcessor.accept(InstallerProcessor.INSTALLERTOOLS, + List.of("--task", "BUNDLER_EXTRACT", "--input", "{MINECRAFT_JAR}", "--output", "{ROOT}/libraries/", "--libraries") + ); + serverProcessor.accept(InstallerProcessor.INSTALLERTOOLS, + List.of("--task", "BUNDLER_EXTRACT", "--input", "{MINECRAFT_JAR}", "--output", "{MC_UNPACKED}", "--jar-only") + ); + var neoformDependency = "net.neoforged:neoform:" + getMcAndNeoFormVersion().get() + "@zip";; + commonProcessor.accept(InstallerProcessor.INSTALLERTOOLS, + List.of("--task", "MCP_DATA", "--input", String.format("[%s]", neoformDependency), "--output", "{MAPPINGS}", "--key", "mappings") + ); + commonProcessor.accept(InstallerProcessor.INSTALLERTOOLS, + List.of("--task", "DOWNLOAD_MOJMAPS", "--version", getMinecraftVersion().get(), "--side", "{SIDE}", "--output", "{MOJMAPS}") + ); + commonProcessor.accept(InstallerProcessor.INSTALLERTOOLS, + List.of("--task", "MERGE_MAPPING", "--left", "{MAPPINGS}", "--right", "{MOJMAPS}", "--output", "{MERGED_MAPPINGS}", "--classes", "--fields", "--methods", "--reverse-right") + ); + clientProcessor.accept(InstallerProcessor.JARSPLITTER, + List.of("--input", "{MINECRAFT_JAR}", "--slim", "{MC_SLIM}", "--extra", "{MC_EXTRA}", "--srg", "{MERGED_MAPPINGS}") + ); + serverProcessor.accept(InstallerProcessor.JARSPLITTER, + List.of("--input", "{MC_UNPACKED}", "--slim", "{MC_SLIM}", "--extra", "{MC_EXTRA}", "--srg", "{MERGED_MAPPINGS}") + ); + commonProcessor.accept(InstallerProcessor.FART, + List.of("--input", "{MC_SLIM}", "--output", "{MC_SRG}", "--names", "{MERGED_MAPPINGS}", "--ann-fix", "--ids-fix", "--src-fix", "--record-fix") + ); + commonProcessor.accept(InstallerProcessor.BINPATCHER, + List.of("--clean", "{MC_SRG}", "--output", "{PATCHED}", "--apply", "{BINPATCH}") + ); + + getLogger().info("Collecting libraries for Installer Profile"); + var profileFiller = new LibraryCollector(getRepositoryURLs().get()); + getLibraries().getAsFileTree().visit(profileFiller); + var libraries = new ArrayList<>(profileFiller.getLibraries()); + + var universalJar = getUniversalJar().getAsFile().get().toPath(); + libraries.add(new Library( + "net.neoforged:neoforge:%s:universal".formatted(getNeoForgeVersion().get()), + new LibraryDownload(new LibraryArtifact( + LibraryCollector.sha1Hash(universalJar), + Files.size(universalJar), + "https://maven.neoforged.net/releases/net/neoforged/neoforge/%s/neoforge-%s-universal.jar".formatted( + getNeoForgeVersion().get(), + getNeoForgeVersion().get()), + "net/neoforged/neoforge/%s/neoforge-%s-universal.jar".formatted( + getNeoForgeVersion().get(), + getNeoForgeVersion().get()) + )))); + + var profile = new InstallerProfile( + "1", + "NeoForge", + "neoforge-%s".formatted(getNeoForgeVersion().get()), + icon, + getMinecraftVersion().get(), + "/version.json", + "/big_logo.png", + "Welcome to the simple NeoForge installer", + "https://mirrors.neoforged.net", + true, + data, + processors, + libraries, + "{LIBRARY_DIR}/net/minecraft/server/{MINECRAFT_VERSION}/server-{MINECRAFT_VERSION}.jar" + ); + + FileUtils.writeStringSafe( + getInstallerProfile().getAsFile().get().toPath(), + new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(profile), + // TODO: Not sure what this should be? Most likely the file is ASCII. + StandardCharsets.UTF_8); + } +} + +record InstallerProfile( + String spec, + String profile, + String version, + String icon, + String minecraft, + String json, + String logo, + String welcome, + String mirrorList, + boolean hideExtract, + Map data, + List processors, + List libraries, + String serverJarPath) {} + +record LauncherDataEntry( + String client, + String server) {} + +record ProcessorEntry( + @Nullable + List sides, + String jar, + List classpath, + List args) {} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/installer/CreateLauncherProfile.java b/buildSrc/src/main/java/net/neoforged/neodev/installer/CreateLauncherProfile.java new file mode 100644 index 00000000000..c2389af6a79 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/installer/CreateLauncherProfile.java @@ -0,0 +1,128 @@ +package net.neoforged.neodev.installer; + +import com.google.gson.GsonBuilder; +import net.neoforged.moddevgradle.internal.utils.FileUtils; +import org.gradle.api.DefaultTask; +import org.gradle.api.file.ConfigurableFileCollection; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.provider.ListProperty; +import org.gradle.api.provider.Property; +import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.InputFiles; +import org.gradle.api.tasks.OutputFile; +import org.gradle.api.tasks.PathSensitive; +import org.gradle.api.tasks.PathSensitivity; +import org.gradle.api.tasks.TaskAction; + +import javax.inject.Inject; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public abstract class CreateLauncherProfile extends DefaultTask { + @Inject + public CreateLauncherProfile() {} + + @Input + public abstract Property getFmlVersion(); + + @Input + public abstract Property getMinecraftVersion(); + + @Input + public abstract Property getNeoForgeVersion(); + + @Input + public abstract Property getRawNeoFormVersion(); + + @InputFiles + @PathSensitive(PathSensitivity.NONE) + public abstract ConfigurableFileCollection getLibraries(); + + @Input + public abstract ListProperty getRepositoryURLs(); + + @Input + public abstract ListProperty getIgnoreList(); + + @InputFiles + @PathSensitive(PathSensitivity.NAME_ONLY) + public abstract ConfigurableFileCollection getModulePath(); + + @OutputFile + public abstract RegularFileProperty getLauncherProfile(); + + @TaskAction + public void createLauncherProfile() throws IOException { + var time = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME); + + getLogger().info("Collecting libraries for Launcher Profile"); + var profileFiller = new LibraryCollector(getRepositoryURLs().get()); + getLibraries().getAsFileTree().visit(profileFiller); + var libraries = profileFiller.getLibraries(); + + var gameArguments = new ArrayList<>(List.of( + "--fml.neoForgeVersion", getNeoForgeVersion().get(), + "--fml.fmlVersion", getFmlVersion().get(), + "--fml.mcVersion", getMinecraftVersion().get(), + "--fml.neoFormVersion", getRawNeoFormVersion().get(), + "--launchTarget", "forgeclient")); + + var jvmArguments = new ArrayList<>(List.of( + "-Djava.net.preferIPv6Addresses=system", + "-DignoreList=" + String.join(",", getIgnoreList().get()), + // TODO: is this still relevant in any way? + "-DmergeModules=jna-5.10.0.jar,jna-platform-5.10.0.jar", + "-DlibraryDirectory=${library_directory}")); + + var modulePathCollector = new ArtifactPathsCollector("${classpath_separator}", "${library_directory}/"); + getModulePath().getAsFileTree().visit(modulePathCollector); + jvmArguments.add("-p"); + jvmArguments.add(modulePathCollector.toString()); + + jvmArguments.addAll(List.of( + "--add-modules", "ALL-MODULE-PATH", + "--add-opens", "java.base/java.util.jar=cpw.mods.securejarhandler", + "--add-opens", "java.base/java.lang.invoke=cpw.mods.securejarhandler", + "--add-exports", "java.base/sun.security.util=cpw.mods.securejarhandler", + "--add-exports", "jdk.naming.dns/com.sun.jndi.dns=java.naming")); + + var arguments = new LinkedHashMap>(); + arguments.put("game", gameArguments); + arguments.put("jvm", jvmArguments); + + var profile = new LauncherProfile( + "neoforge-%s".formatted(getNeoForgeVersion().get()), + time, + time, + "release", + "cpw.mods.bootstraplauncher.BootstrapLauncher", + getMinecraftVersion().get(), + arguments, + libraries + ); + + FileUtils.writeStringSafe( + getLauncherProfile().getAsFile().get().toPath(), + new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(profile), + // TODO: Not sure what this should be? Most likely the file is ASCII. + StandardCharsets.UTF_8); + } +} + +record LauncherProfile( + String id, + String time, + String releaseTime, + String type, + String mainClass, + String inheritsFrom, + Map> arguments, + List libraries) {} + diff --git a/buildSrc/src/main/java/net/neoforged/neodev/installer/InstallerProcessor.java b/buildSrc/src/main/java/net/neoforged/neodev/installer/InstallerProcessor.java new file mode 100644 index 00000000000..e5c5b60b45a --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/installer/InstallerProcessor.java @@ -0,0 +1,16 @@ +package net.neoforged.neodev.installer; + +import net.neoforged.neodev.Tools; + +public enum InstallerProcessor { + BINPATCHER(Tools.BINPATCHER), + FART(Tools.AUTO_RENAMING_TOOL), + INSTALLERTOOLS(Tools.INSTALLERTOOLS), + JARSPLITTER(Tools.JARSPLITTER); + + public final Tools tool; + + InstallerProcessor(Tools tool) { + this.tool = tool; + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/installer/Library.java b/buildSrc/src/main/java/net/neoforged/neodev/installer/Library.java new file mode 100644 index 00000000000..d064dfa4dad --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/installer/Library.java @@ -0,0 +1,5 @@ +package net.neoforged.neodev.installer; + +record Library( + String name, + LibraryDownload downloads) {} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryArtifact.java b/buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryArtifact.java new file mode 100644 index 00000000000..1e345980e9a --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryArtifact.java @@ -0,0 +1,7 @@ +package net.neoforged.neodev.installer; + +record LibraryArtifact( + String sha1, + long size, + String url, + String path) {} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryCollector.java b/buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryCollector.java new file mode 100644 index 00000000000..e9a086c6cbc --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryCollector.java @@ -0,0 +1,220 @@ +package net.neoforged.neodev.installer; + +import org.gradle.api.artifacts.component.ModuleComponentIdentifier; +import org.gradle.api.artifacts.result.ResolvedArtifactResult; +import org.gradle.api.logging.Logger; +import org.gradle.api.logging.Logging; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Future; +import java.util.function.Function; + +class LibraryCollector extends ModuleIdentificationVisitor { + private static final Logger LOGGER = Logging.getLogger(LibraryCollector.class); + /** + * Hosts from which we allow the installer to download. + * We whitelist here to avoid redirecting player download traffic to anyone not affiliated with Mojang or us. + */ + private static final List HOST_WHITELIST = List.of( + "minecraft.net", + "neoforged.net", + "mojang.com" + ); + + private static final URI MOJANG_MAVEN = URI.create("https://libraries.minecraft.net"); + private static final URI NEOFORGED_MAVEN = URI.create("https://maven.neoforged.net/releases"); + + private final List repositoryUrls; + + private final List> libraries = new ArrayList<>(); + + private final HttpClient httpClient = HttpClient.newBuilder().build(); + + LibraryCollector(List repoUrl) { + this.repositoryUrls = new ArrayList<>(repoUrl); + + // Only remote repositories make sense (no maven local) + repositoryUrls.removeIf(it -> { + var lowercaseScheme = it.getScheme().toLowerCase(Locale.ROOT); + return !lowercaseScheme.equals("https") && !lowercaseScheme.equals("http"); + }); + // Allow only URLs from whitelisted hosts + repositoryUrls.removeIf(uri -> { + var lowercaseHost = uri.getHost().toLowerCase(Locale.ROOT); + return HOST_WHITELIST.stream().noneMatch(it -> lowercaseHost.equals(it) || lowercaseHost.endsWith("." + it)); + }); + // Always try Mojang Maven first, then our installer Maven + repositoryUrls.removeIf(it -> it.getHost().equals(MOJANG_MAVEN.getHost())); + repositoryUrls.removeIf(it -> it.getHost().equals(NEOFORGED_MAVEN.getHost()) && it.getPath().startsWith(NEOFORGED_MAVEN.getPath())); + repositoryUrls.add(0, NEOFORGED_MAVEN); + repositoryUrls.add(0, MOJANG_MAVEN); + + LOGGER.info("Collecting libraries from:"); + for (var repo : repositoryUrls) { + LOGGER.info(" - " + repo); + } + } + + void visit(ResolvedArtifactResult artifactResult) throws IOException { + var componentId = artifactResult.getId().getComponentIdentifier(); + if (componentId instanceof ModuleComponentIdentifier moduleComponentId) { + visitModule( + artifactResult.getFile(), + moduleComponentId.getGroup(), + moduleComponentId.getModule(), + moduleComponentId.getVersion(), + guessMavenClassifier(artifactResult.getFile(), moduleComponentId), + getExtension(artifactResult.getFile().getName()) + ); + } else { + LOGGER.warn("Cannot handle component: " + componentId); + } + } + + private static String guessMavenClassifier(File file, ModuleComponentIdentifier id) { + var artifact = id.getModule(); + var version = id.getVersion(); + var expectedBasename = artifact + "-" + version; + var filename = file.getName(); + var startOfExt = filename.lastIndexOf('.'); + if (startOfExt != -1) { + filename = filename.substring(0, startOfExt); + } + + if (filename.startsWith(expectedBasename + "-")) { + return filename.substring((expectedBasename + "-").length()); + } + return ""; + } + + /** + * The filename includes the period. + */ + private static String getExtension(String path) { + var lastSep = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + + var potentialExtension = path.lastIndexOf('.'); + if (potentialExtension > lastSep) { + // Check for a double extension like .tar.gz heuristically + var doubleExtensionStart = path.lastIndexOf('.', potentialExtension - 1); + // We only allow 3 chars maximum for the double extension + if (doubleExtensionStart > lastSep && potentialExtension - doubleExtensionStart <= 4) { + return path.substring(doubleExtensionStart); + } + + return path.substring(potentialExtension); + } else { + return ""; + } + } + + @Override + protected void visitModule(File file, String group, String module, String version, String classifier, final String extension) throws IOException { + final String name = group + ":" + module + ":" + version + (classifier.isEmpty() ? "" : ":" + classifier) + "@" + extension; + final String path = group.replace(".", "/") + "/" + module + "/" + version + "/" + module + "-" + version + (classifier.isEmpty() ? "" : "-" + classifier) + "." + extension; + + var sha1 = sha1Hash(file.toPath()); + var fileSize = Files.size(file.toPath()); + + // Try each configured repository in-order to find the file + CompletableFuture libraryFuture = null; + for (var repositoryUrl : repositoryUrls) { + var artifactUri = joinUris(repositoryUrl, path); + var request = HttpRequest.newBuilder(artifactUri) + .method("HEAD", HttpRequest.BodyPublishers.noBody()) + .build(); + + Function> makeRequest = (String previousError) -> { + return httpClient.sendAsync(request, HttpResponse.BodyHandlers.discarding()) + .thenApply(response -> { + if (response.statusCode() != 200) { + LOGGER.info(" Got %d for %s".formatted(response.statusCode(), artifactUri)); + String message = "Could not find %s: %d".formatted(artifactUri, response.statusCode()); + // Prepend error message from previous repo if they all fail + if (previousError != null) { + message = previousError + "\n" + message; + } + throw new RuntimeException(message); + } + LOGGER.info(" Found $name -> $artifactUri"); + return new Library( + name, + new LibraryDownload(new LibraryArtifact( + sha1, + fileSize, + artifactUri.toString(), + path))); + }); + }; + + if (libraryFuture == null) { + libraryFuture = makeRequest.apply(null); + } else { + libraryFuture = libraryFuture.exceptionallyCompose(error -> { + return makeRequest.apply(error.getMessage()); + }); + } + } + + libraries.add(libraryFuture); + } + + static String sha1Hash(Path path) throws IOException { + MessageDigest digest; + try { + digest = MessageDigest.getInstance("SHA-1"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + + try (var in = Files.newInputStream(path); + var din = new DigestInputStream(in, digest)) { + byte[] buffer = new byte[8192]; + while (din.read(buffer) != -1) { + } + } + + return HexFormat.of().formatHex(digest.digest()); + } + + private static URI joinUris(URI repositoryUrl, String path) { + var baseUrl = repositoryUrl.toString(); + if (baseUrl.endsWith("/") && path.startsWith("/")) { + while (path.startsWith("/")) { + path = path.substring(1); + } + return URI.create(baseUrl + path); + } else if (!baseUrl.endsWith("/") && !path.startsWith("/")) { + return URI.create(baseUrl + "/" + path); + } else { + return URI.create(baseUrl + path); + } + } + + List getLibraries() { + var result = libraries.stream().map(future -> { + try { + return future.get(); + } catch (Exception e) { + throw new RuntimeException(e); + } + }).toList(); + LOGGER.info("Collected %d libraries".formatted(result.size())); + return result; + } +} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryDownload.java b/buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryDownload.java new file mode 100644 index 00000000000..38afe5d0576 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/installer/LibraryDownload.java @@ -0,0 +1,4 @@ +package net.neoforged.neodev.installer; + +record LibraryDownload( + LibraryArtifact artifact) {} diff --git a/buildSrc/src/main/java/net/neoforged/neodev/installer/ModuleIdentificationVisitor.java b/buildSrc/src/main/java/net/neoforged/neodev/installer/ModuleIdentificationVisitor.java new file mode 100644 index 00000000000..9682244dab5 --- /dev/null +++ b/buildSrc/src/main/java/net/neoforged/neodev/installer/ModuleIdentificationVisitor.java @@ -0,0 +1,51 @@ +package net.neoforged.neodev.installer; + +import org.gradle.api.file.FileVisitDetails; +import org.gradle.api.file.FileVisitor; + +import java.io.File; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +// TODO: simplify this class and subclasses if possible +abstract class ModuleIdentificationVisitor implements FileVisitor { + + // The following regex detects file path patterns, in gradle cache format. Like: /net.neoforged.fancymodloader/earlydisplay/47.1.47/46509b19504a71e25b115383e900aade5088598a/earlydisplay-47.1.47.jar + private static final Pattern GRADLE_CACHE_PATTERN = Pattern.compile("/(?[^/]+)/(?[^/]+)/(?[^/]+)/(?[a-z0-9]+)/\\k-\\k(-(?[^/]+))?\\.(?(jar)|(zip))$"); + + // The following regex detects file path patterns, in maven local cache format. Like: /.m2/repository/com/google/code/findbugs/jsr305/3.0.2/jsr305-3.0.2.jar + private static final Pattern MAVEN_LOCAL_PATTERN = Pattern.compile("/.m2/repository/(?.+)/(?[^/]+)/(?[^/]+)/\\k-\\k(-(?[^/]+))?\\.(?(jar)|(zip))$"); + + @Override + public void visitDir(FileVisitDetails dirDetails) { + //Noop + } + + @Override + public void visitFile(FileVisitDetails fileDetails) { + File file = fileDetails.getFile(); + String absolutePath = file.getAbsolutePath().replace("\\", "/"); + + Matcher matcher = GRADLE_CACHE_PATTERN.matcher(absolutePath); + if (!matcher.find()) { + matcher = MAVEN_LOCAL_PATTERN.matcher(absolutePath); + if (!matcher.find()) { + throw new IllegalStateException("Cannot determine the GAV of " + file + ", since it is neither a remote nor a Maven local dependency!"); + } + } + + String group = matcher.group("group").replace("/", "."); //In case we match the maven way. + String module = matcher.group("module"); + String version = matcher.group("version"); + String classifier = matcher.group("classifier") == null ? "" : matcher.group("classifier"); + String extension = matcher.group("extension"); + + try { + visitModule(file, group, module, version, classifier, extension); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + protected abstract void visitModule(File file, String group, String module, String version, String classifier, String extension) throws Exception; +} diff --git a/gradle.properties b/gradle.properties index 8022687928b..6e295af7fd1 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,8 +4,11 @@ org.gradle.jvmargs=-Xmx3G org.gradle.daemon=true org.gradle.parallel=true org.gradle.caching=true -org.gradle.configuration-cache=false +org.gradle.configuration-cache=true org.gradle.debug=false +org.gradle.warning.mode=fail + +moddevgradle_plugin_version=2.0.40-beta java_version=21 @@ -14,6 +17,12 @@ neoform_version=20240808.144430 # on snapshot versions, used to prefix the version neoforge_snapshot_next_stable=22.0 +jst_version=1.0.45 +legacyinstaller_version=3.0.27 +art_version=2.0.3 +installertools_version=2.1.2 +devlaunch_version=1.0.1 + mergetool_version=2.0.0 accesstransformers_version=10.0.1 coremods_version=6.0.4 @@ -22,7 +31,6 @@ modlauncher_version=11.0.4 securejarhandler_version=3.0.8 bootstraplauncher_version=2.0.2 asm_version=9.5 -installer_version=2.1.+ mixin_version=0.14.0+mixin.0.8.6 terminalconsoleappender_version=1.3.0 nightconfig_version=3.8.0 @@ -48,7 +56,3 @@ vintage_engine_version=5.+ assertj_core=3.25.1 neogradle.runtime.platform.installer.debug=true -# We want to be able to have a junit run disconnected from the test and main sourcesets -neogradle.subsystems.conventions.sourcesets.automatic-inclusion=false -neogradle.subsystems.conventions.enabled=false -neogradle.subsystems.tools.jst=net.neoforged.jst:jst-cli-bundle:1.0.45 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index b82aa23a4f0..0aaefbcaf0f 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.7-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/projects/base/build.gradle b/projects/base/build.gradle index 7a78b9aa79c..1a1f878f9a7 100644 --- a/projects/base/build.gradle +++ b/projects/base/build.gradle @@ -1,3 +1,15 @@ -dynamicProject { - neoform("${project.minecraft_version}-${project.neoform_version}") + +plugins { + id 'java-library' +} + +apply plugin: net.neoforged.neodev.NeoDevBasePlugin + +dependencies { + implementation("net.neoforged:neoform:${project.minecraft_version}-${project.neoform_version}") { + capabilities { + requireCapability 'net.neoforged:neoform-dependencies' + } + endorseStrictVersions() + } } diff --git a/projects/neoforge/build.gradle b/projects/neoforge/build.gradle index 0393b5455b4..ceced5f4b52 100644 --- a/projects/neoforge/build.gradle +++ b/projects/neoforge/build.gradle @@ -1,14 +1,18 @@ -import net.neoforged.jarcompatibilitychecker.gradle.JCCPlugin -import net.neoforged.jarcompatibilitychecker.gradle.ProvideNeoForgeJarTask + +// TODO re-enable +//import net.neoforged.jarcompatibilitychecker.gradle.JCCPlugin +//import net.neoforged.jarcompatibilitychecker.gradle.ProvideNeoForgeJarTask plugins { id 'java-library' id 'maven-publish' - id 'net.neoforged.jarcompatibilitychecker' version '0.1.9' + // TODO re-enable id 'net.neoforged.jarcompatibilitychecker' version '0.1.9' id 'net.neoforged.gradleutils' id 'neoforge.versioning' } +apply plugin : net.neoforged.neodev.NeoDevPlugin + gradleutils.setupSigning(project: project, signAllPublications: true) changelog { @@ -16,54 +20,6 @@ changelog { disableAutomaticPublicationRegistration() } -dynamicProject { - runtime("${project.minecraft_version}-${project.neoform_version}", - rootProject.layout.projectDirectory.dir('patches'), - rootProject.layout.projectDirectory.dir('rejects')) -} - -final checkVersion = JCCPlugin.providePreviousVersion( - project.providers, project.providers.provider({['https://maven.neoforged.net/releases']}), project.providers.provider({'net.neoforged:neoforge'}) -) -final createCompatJar = tasks.register('createCompatibilityCheckJar', ProvideNeoForgeJarTask) { - // Use the same jar that the patches were generated against - cleanJar.set(tasks.generateClientBinaryPatches.clean) - maven.set('https://maven.neoforged.net/releases') - artifact.set('net.neoforged:neoforge') - version.set(checkVersion) - javaLauncher = javaToolchains.launcherFor { - languageVersion = JavaLanguageVersion.of(java_version) - } -} -checkJarCompatibility { - isAPI = true - baseJar = createCompatJar.flatMap { it.output } -} - -installerProfile { - profile = 'NeoForge' -} - -minecraft { - // FML looks for this mod id to find the minecraft classes - modIdentifier 'minecraft' - - accessTransformers { - file rootProject.file('src/main/resources/META-INF/accesstransformer.cfg') - } -} - -tasks.configureEach { tsk -> - if (tsk.name == 'neoFormApplyUserAccessTransformer' && project.hasProperty('validateAccessTransformers')) { - tsk.inputs.property('validation', 'error') - tsk.logLevel('ERROR') - tsk.doFirst { - tsk.getRuntimeProgramArguments().addAll(tsk.getRuntimeProgramArguments().get()) - tsk.getRuntimeProgramArguments().add('--access-transformer-validation=error') - } - } -} - sourceSets { main { java { @@ -75,7 +31,69 @@ sourceSets { } } +// TODO re-enable +//final checkVersion = JCCPlugin.providePreviousVersion( +// project.providers, project.providers.provider({['https://maven.neoforged.net/releases']}), project.providers.provider({'net.neoforged:neoforge'}) +//) +//final createCompatJar = tasks.register('createCompatibilityCheckJar', ProvideNeoForgeJarTask) { +// // Use the same jar that the patches were generated against +// cleanJar.set(tasks.generateClientBinaryPatches.clean) +// maven.set('https://maven.neoforged.net/releases') +// artifact.set('net.neoforged:neoforge') +// version.set(checkVersion) +// javaLauncher = javaToolchains.launcherFor { +// languageVersion = JavaLanguageVersion.of(java_version) +// } +//} +//checkJarCompatibility { +// isAPI = true +// baseJar = createCompatJar.flatMap { it.output } +//} +// +//tasks.configureEach { tsk -> +// if (tsk.name == 'neoFormApplyUserAccessTransformer' && project.hasProperty('validateAccessTransformers')) { +// tsk.inputs.property('validation', 'error') +// tsk.logLevel('ERROR') +// tsk.doFirst { +// tsk.getRuntimeProgramArguments().addAll(tsk.getRuntimeProgramArguments().get()) +// tsk.getRuntimeProgramArguments().add('--access-transformer-validation=error') +// } +// } +//} + +neoDev { + mods { + minecraft { + sourceSet sourceSets.main + } + } +} + +configurations { + installer { + // TODO: shouldn't have both on + canBeResolved = true + canBeConsumed = true + } + installerLibraries { + extendsFrom installer + } + moduleOnly { + // TODO: shouldn't have both on + canBeResolved = true + canBeConsumed = true + } + implementation.extendsFrom installer +} + dependencies { + implementation("net.neoforged:neoform:${project.minecraft_version}-${project.neoform_version}") { + capabilities { + requireCapability 'net.neoforged:neoform-dependencies' + } + endorseStrictVersions() + } + runtimeOnly "cpw.mods:bootstraplauncher:${project.bootstraplauncher_version}" moduleOnly "cpw.mods:securejarhandler:${project.securejarhandler_version}" @@ -126,117 +144,39 @@ dependencies { installer "org.apache.logging.log4j:log4j-api:${project.log4j_version}" installer "org.apache.logging.log4j:log4j-core:${project.log4j_version}" + installerLibraries "net.neoforged:neoform:${project.minecraft_version}-${project.neoform_version}@zip" + compileOnly "org.jetbrains:annotations:${project.jetbrains_annotations_version}" - userdevCompileOnly jarJar("io.github.llamalad7:mixinextras-neoforge:${project.mixin_extras_version}"), { - jarJar.ranged(it, "[${project.mixin_extras_version},)") - } + userdevCompileOnly jarJar("io.github.llamalad7:mixinextras-neoforge:${project.mixin_extras_version}") + // TODO: duplicated with the text fixtures userdevTestImplementation("net.neoforged.fancymodloader:junit-fml:${project.fancy_mod_loader_version}") } -runTypes { - client { - singleInstance false - client true - - arguments.addAll '--fml.neoForgeVersion', project.version - arguments.addAll '--fml.fmlVersion', project.fancy_mod_loader_version - arguments.addAll '--fml.mcVersion', project.minecraft_version - arguments.addAll '--fml.neoFormVersion', project.neoform_version - } - - server { - server true - - arguments.addAll '--fml.neoForgeVersion', project.version - arguments.addAll '--fml.fmlVersion', project.fancy_mod_loader_version - arguments.addAll '--fml.mcVersion', project.minecraft_version - arguments.addAll '--fml.neoFormVersion', project.neoform_version - } - - gameTestServer { - from project.runTypes.server - - gameTest true - } - - gameTestClient { - from project.runTypes.client - - gameTest true - } - - data { - dataGenerator true - - // Don't set modid here so we can reuse this runType for test datagen - arguments.addAll '--fml.neoForgeVersion', project.version - arguments.addAll '--fml.fmlVersion', project.fancy_mod_loader_version - arguments.addAll '--fml.mcVersion', project.minecraft_version - arguments.addAll '--fml.neoFormVersion', project.neoform_version - } - - junit { - junit true - arguments.addAll '--fml.neoForgeVersion', project.version - arguments.addAll '--fml.fmlVersion', project.fancy_mod_loader_version - arguments.addAll '--fml.mcVersion', project.minecraft_version - arguments.addAll '--fml.neoFormVersion', project.neoform_version - } -} - -runs { - client { } - server { } - gameTestServer { } - gameTestClient { } - data { - programArguments.addAll '--mod', 'neoforge' - - modSources.add project.sourceSets.main - - idea { - primarySourceSet project.sourceSets.main +neoDev { + runs { + configureEach { + gameDirectory.set project.file("run/${it.name}") as File + } + client { + client() + } + server { + server() + } + gameTestServer { + type = "gameTestServer" + } + data { + data() + programArguments.addAll '--mod', 'neoforge', '--flat', '--all', '--validate', + '--existing', rootProject.file("src/main/resources").absolutePath, + '--output', rootProject.file("src/generated/resources").absolutePath } } } -runs.configureEach { it -> - final File gameDir = project.file("run/${it.name}") as File - gameDir.mkdirs(); - - it.workingDirectory.set gameDir - it.programArguments.addAll '--gameDir', gameDir.absolutePath -} - -launcherProfile { - arguments { - game '--fml.neoForgeVersion' - game project.version - game '--fml.fmlVersion' - game project.fancy_mod_loader_version - game '--fml.mcVersion' - game project.minecraft_version - game '--fml.neoFormVersion' - game project.neoform_version - } -} - -userdevProfile { - runTypes.configureEach { - argument '--fml.neoForgeVersion' - argument project.version - argument '--fml.fmlVersion' - argument project.fancy_mod_loader_version - argument '--fml.mcVersion' - argument project.minecraft_version - argument '--fml.neoFormVersion' - argument project.neoform_version - } - additionalTestDependencyArtifactCoordinate "net.neoforged:testframework:${project.version}" -} - tasks.withType(Javadoc.class).configureEach { options.tags = [ 'apiNote:a:API Note:', @@ -346,9 +286,7 @@ configurations { modDevApiElements { canBeResolved = false canBeConsumed = true - afterEvaluate { - extendsFrom userdevCompileOnly, installerLibraries, moduleOnly - } + extendsFrom userdevCompileOnly, installerLibraries, moduleOnly attributes { attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category, Category.LIBRARY)) attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling, Bundling.EXTERNAL)) @@ -431,38 +369,35 @@ dependencies { processResources { inputs.property("version", project.version) + final version = project.version filesMatching("META-INF/neoforge.mods.toml") { expand([ "global": [ - "neoForgeVersion": project.version + "neoForgeVersion": version ] ]) } } -afterEvaluate { - artifacts { - modDevBundle(userdevJar) { - setClassifier("userdev") // Legacy - } - modDevConfig(createUserdevJson.output) { - builtBy(createUserdevJson) - setClassifier("moddev-config") - } - universalJar(signUniversalJar.output) { - builtBy(signUniversalJar) - setClassifier("universal") - } - installerJar(signInstallerJar.output) { - builtBy(signInstallerJar) - setClassifier("installer") - } - changelog(createChangelog.outputFile) { - builtBy(createChangelog) - setClassifier("changelog") - setExtension("txt") - } - } +artifacts { + modDevBundle(userdevJar) { + setClassifier("userdev") // Legacy + } + modDevConfig(writeUserDevConfig.userDevConfig) { + setClassifier("moddev-config") + } + universalJar(universalJar) { + setClassifier("universal") + } +// installerJar(signInstallerJar.output) { +// builtBy(signInstallerJar) +// setClassifier("installer") +// } +// changelog(createChangelog.outputFile) { +// builtBy(createChangelog) +// setClassifier("changelog") +// setExtension("txt") +// } } publishing { diff --git a/settings.gradle b/settings.gradle index 33563e53503..4aca3a4d8d0 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,25 +1,35 @@ pluginManagement { repositories { gradlePluginPortal() - mavenLocal() maven { url = 'https://maven.neoforged.net/releases' } + mavenLocal() } } plugins { - id 'net.neoforged.gradle.platform' version '7.0.150' + id 'net.neoforged.moddev.repositories' version "${moddevgradle_plugin_version}" + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' } -rootProject.name = rootDir.name +// This makes the version available to buildSrc +gradle.ext.moddevgradle_plugin_version = moddevgradle_plugin_version -dynamicProjects { - include ':base' - include ':neoforge' - - project(":base").projectDir = file("projects/base") - project(":neoforge").projectDir = file("projects/neoforge") +dependencyResolutionManagement { + repositoriesMode = RepositoriesMode.FAIL_ON_PROJECT_REPOS + rulesMode = RulesMode.FAIL_ON_PROJECT_RULES + repositories { + mavenCentral() + mavenLocal() + } } +rootProject.name = rootDir.name + +include ':base' +project(':base').projectDir = file('projects/base') +include ':neoforge' +project(':neoforge').projectDir = file('projects/neoforge') + include ':tests' project(":tests").projectDir = file("tests") diff --git a/testframework/build.gradle b/testframework/build.gradle index 91a01c1c760..d5d98b4059a 100644 --- a/testframework/build.gradle +++ b/testframework/build.gradle @@ -3,25 +3,19 @@ plugins { id 'maven-publish' id 'com.diffplug.spotless' id 'net.neoforged.licenser' - id 'net.neoforged.gradle.platform' id 'neoforge.formatting-conventions' } java.withSourcesJar() -repositories { - maven { - name 'Mojang' - url 'https://libraries.minecraft.net' - } - maven { - name 'NeoForged' - url 'https://maven.neoforged.net/releases' - } -} +apply plugin : net.neoforged.minecraftdependencies.MinecraftDependenciesPlugin dependencies { - implementation project(path: ':neoforge', configuration: 'runtimeElements') + // TODO: is this leaking in the POM? (most likely yes) + // TODO: does this need to be changed back to runtimeDependencies? + // TODO: should use attributes to resolve the right variant instead of hardcoding + compileOnly project(path: ':neoforge', configuration: 'apiElements') + runtimeOnly project(path: ':neoforge', configuration: 'runtimeElements') compileOnly(platform("org.junit:junit-bom:${project.jupiter_api_version}")) compileOnly "org.junit.jupiter:junit-jupiter-params" @@ -30,6 +24,14 @@ dependencies { compileOnly "com.google.code.findbugs:jsr305:3.0.2" } +sourceSets { + main { + // TODO: cursed + compileClasspath += project(':neoforge').sourceSets.main.compileClasspath + runtimeClasspath += project(':neoforge').sourceSets.main.runtimeClasspath + } +} + license { header = rootProject.file('codeformat/HEADER.txt') include '**/*.java' @@ -39,6 +41,7 @@ tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8' } +def version = project.version tasks.withType(ProcessResources).configureEach { inputs.properties version: version diff --git a/tests/build.gradle b/tests/build.gradle index 83f5f7dcc0f..fa4fbb2bcbd 100644 --- a/tests/build.gradle +++ b/tests/build.gradle @@ -1,37 +1,26 @@ + plugins { id 'java' - id 'net.neoforged.gradle.platform' id 'com.diffplug.spotless' id 'net.neoforged.licenser' id 'neoforge.formatting-conventions' } +apply plugin : net.neoforged.neodev.NeoDevExtraPlugin + +evaluationDependsOn(":neoforge") + def neoforgeProject = project(':neoforge') def testframeworkProject = project(':testframework') -repositories { - mavenLocal() - maven { - name 'Mojang' - url 'https://libraries.minecraft.net' - } - maven { - name 'NeoForged' - url 'https://maven.neoforged.net/releases' - } -} - sourceSets { main { resources { srcDir file('src/generated/resources') } } - junit {} -} - -configurations { - junitImplementation.extendsFrom(implementation) + junit { + } } dependencies { @@ -44,72 +33,78 @@ dependencies { junitImplementation("org.assertj:assertj-core:${project.assertj_core}") junitImplementation "net.neoforged.fancymodloader:junit-fml:${project.fancy_mod_loader_version}" + junitImplementation project(path: ':neoforge', configuration: 'runtimeElements') + junitImplementation(testframeworkProject) compileOnly "org.jetbrains:annotations:${project.jetbrains_annotations_version}" } +// Required to fix compile classpath using an older junit version. Alternatively we could also just bump junit. +configurations.junitCompileClasspath.shouldResolveConsistentlyWith configurations.junitRuntimeClasspath -runs { - client { - configure neoforgeProject.runTypes.client - } - junit { - configure neoforgeProject.runTypes.junit - unitTestSource sourceSets.junit - } - server { - configure neoforgeProject.runTypes.server - } - gameTestServer { - configure neoforgeProject.runTypes.gameTestServer - } - gameTestClient { - configure neoforgeProject.runTypes.gameTestClient +junitTest { + useJUnitPlatform() + classpath = sourceSets.junit.output + sourceSets.junit.runtimeClasspath + testClassesDirs = sourceSets.junit.output.classesDirs + outputs.upToDateWhen { false } +} + +neoDev { + mods { + neotests { + sourceSet sourceSets.main + } + testframework { + sourceSet project(":testframework").sourceSets.main + } + junit { + sourceSet sourceSets.junit + } } - data { - configure neoforgeProject.runTypes.data - - programArguments.addAll '--flat', '--all', '--validate', - '--mod', 'data_gen_test', - '--mod', 'global_loot_test', - '--mod', 'scaffolding_test', - '--mod', 'custom_tag_types_test', - '--mod', 'new_model_loader_test', - '--mod', 'remove_tag_datagen_test', - '--mod', 'tag_based_tool_types', - '--mod', 'custom_transformtype_test', - '--mod', 'data_pack_registries_test', - '--mod', 'biome_modifiers_test', - '--mod', 'structure_modifiers_test', - '--mod', 'custom_preset_editor_test', - '--mod', 'custom_predicate_test', - '--mod', 'neotests', - '--existing-mod', 'testframework', - '--existing', sourceSets.main.resources.srcDirs[0].absolutePath - - final File gameDir = project.file("runs/${name}") as File - gameDir.mkdirs(); - - workingDirectory.set gameDir - programArguments.addAll '--gameDir', gameDir.absolutePath + + runs { + client { + client() + } + server { + server() + } + gameTestServer { + type = "gameTestServer" + } + data { + data() + + programArguments.addAll '--flat', '--all', '--validate', + '--mod', 'data_gen_test', + '--mod', 'global_loot_test', + '--mod', 'scaffolding_test', + '--mod', 'custom_tag_types_test', + '--mod', 'new_model_loader_test', + '--mod', 'remove_tag_datagen_test', + '--mod', 'tag_based_tool_types', + '--mod', 'custom_transformtype_test', + '--mod', 'data_pack_registries_test', + '--mod', 'biome_modifiers_test', + '--mod', 'structure_modifiers_test', + '--mod', 'custom_preset_editor_test', + '--mod', 'custom_predicate_test', + '--mod', 'neotests', + '--existing-mod', 'testframework', + '--existing', project.file("src/main/resources").absolutePath, + '--output', project.file("src/generated/resources").absolutePath + } } -} -//We need the assets and natives tasks from the forge project. -runs.configureEach { - dependsOn(neoforgeProject.runtime.assets, neoforgeProject.runtime.natives) - modSource neoforgeProject.sourceSets.main - modSource testframeworkProject.sourceSets.main -} + runs.configureEach { + // Add NeoForge and Minecraft (both under the "minecraft" mod), and exclude junit. + loadedMods = [neoforgeProject.neoDev.mods.minecraft, mods.neotests, mods.testframework] -afterEvaluate { - runs.data { - // Override --output that forge already has - def args = new ArrayList(programArguments.get()); - def outputIndex = args.indexOf('--output'); - args.set(outputIndex+1, file('src/generated/resources/').absolutePath); - programArguments.set(args); + gameDirectory.set project.file("runs/${it.name}") as File } - runs.junit.modSources.all().get().values().remove(sourceSets.main) +} + +neoDevTest { + loadedMods = [ project(":neoforge").neoDev.mods.minecraft, neoDev.mods.testframework, neoDev.mods.junit ] } license {