General cleanup by making use of java 16 features (#397)

* General cleanup by making use of java 16 features

* use jackson-databind in place of gson when reading to a record

* Fixes

* cleanup

* dep updates

* Replace commons IOUtils usage with native java

* Update fernflower
dev/0.11
modmuss50 2021-05-13 22:06:34 +01:00 committed by GitHub
parent 2f38c747a1
commit 9fb167d506
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 163 additions and 430 deletions

View File

@ -6,8 +6,8 @@ A [Gradle](https://gradle.org/) plugin to setup a deobfuscated development envir
* Utilises the Fernflower and CFR decompilers to generate source code with comments. * Utilises the Fernflower and CFR decompilers to generate source code with comments.
* Designed to support modern versions of Minecraft (Tested with 1.14.4 and upwards) * Designed to support modern versions of Minecraft (Tested with 1.14.4 and upwards)
* Built in support for IntelliJ IDEA, Eclipse and Visual Studio Code to generate run configurations for Minecraft. * Built in support for IntelliJ IDEA, Eclipse and Visual Studio Code to generate run configurations for Minecraft.
* Loom targets a wide range of Gradle versions. _Tested with 4.9 up to 6.7_ * Loom targets the latest version of Gradle 7 or newer
* Supports the latest version of Java all the way down to Java 8 * Supports Java 16 upwards
## Use Loom to develop mods ## Use Loom to develop mods

View File

@ -46,6 +46,7 @@ dependencies {
implementation ('commons-io:commons-io:2.8.0') implementation ('commons-io:commons-io:2.8.0')
implementation ('org.zeroturnaround:zt-zip:1.14') implementation ('org.zeroturnaround:zt-zip:1.14')
implementation ('com.google.code.gson:gson:2.8.6') implementation ('com.google.code.gson:gson:2.8.6')
implementation ('com.fasterxml.jackson.core:jackson-databind:2.12.3')
implementation ('com.google.guava:guava:30.1-jre') implementation ('com.google.guava:guava:30.1-jre')
implementation ('org.ow2.asm:asm:9.1') implementation ('org.ow2.asm:asm:9.1')
implementation ('org.ow2.asm:asm-analysis:9.1') implementation ('org.ow2.asm:asm-analysis:9.1')
@ -70,21 +71,21 @@ dependencies {
implementation ('org.cadixdev:lorenz-io-proguard:0.5.6') implementation ('org.cadixdev:lorenz-io-proguard:0.5.6')
// decompilers // decompilers
implementation ('net.fabricmc:fabric-fernflower:1.3.0') implementation ('net.fabricmc:fabric-fernflower:1.4.0')
implementation ('org.benf:cfr:0.150') implementation ('org.benf:cfr:0.151')
// source code remapping // source code remapping
implementation ('org.cadixdev:mercury:0.1.0-rc1') implementation ('org.cadixdev:mercury:0.1.0-rc1')
// Kapt integration // Kapt integration
compileOnly('org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.32') compileOnly('org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0')
// Testing // Testing
testImplementation(gradleTestKit()) testImplementation(gradleTestKit())
testImplementation('org.spockframework:spock-core:2.0-M5-groovy-3.0') { testImplementation('org.spockframework:spock-core:2.0-M5-groovy-3.0') {
exclude module: 'groovy-all' exclude module: 'groovy-all'
} }
testImplementation 'io.javalin:javalin:3.13.4' testImplementation 'io.javalin:javalin:3.13.7'
compileOnly 'org.jetbrains:annotations:20.1.0' compileOnly 'org.jetbrains:annotations:20.1.0'
} }
@ -115,11 +116,11 @@ license {
checkstyle { checkstyle {
configFile = file('checkstyle.xml') configFile = file('checkstyle.xml')
toolVersion = '8.41.1' toolVersion = '8.42'
} }
codenarc { codenarc {
toolVersion = "2.0.0" toolVersion = "2.1.0"
configFile = file("codenarc.groovy") configFile = file("codenarc.groovy")
} }

View File

@ -24,6 +24,8 @@
package net.fabricmc.loom; package net.fabricmc.loom;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@ -41,6 +43,7 @@ import net.fabricmc.loom.task.LoomTasks;
public class LoomGradlePlugin implements Plugin<Project> { public class LoomGradlePlugin implements Plugin<Project> {
public static boolean refreshDeps; public static boolean refreshDeps;
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
@Override @Override
public void apply(Project project) { public void apply(Project project) {

View File

@ -27,14 +27,5 @@ package net.fabricmc.loom.api.decompilers;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Collection; import java.util.Collection;
public class DecompilationMetadata { public record DecompilationMetadata(int numberOfThreads, Path javaDocs, Collection<Path> libraries) {
public final int numberOfThreads;
public final Path javaDocs;
public final Collection<Path> libraries;
public DecompilationMetadata(int numberOfThreads, Path javaDocs, Collection<Path> libraries) {
this.numberOfThreads = numberOfThreads;
this.javaDocs = javaDocs;
this.libraries = libraries;
}
} }

View File

@ -69,7 +69,7 @@ public class ModCompileRemapper {
for (RemappedConfigurationEntry entry : Constants.MOD_COMPILE_ENTRIES) { for (RemappedConfigurationEntry entry : Constants.MOD_COMPILE_ENTRIES) {
data.getLazyConfigurationProvider(entry.getRemappedConfiguration()).configure(remappedConfig -> { data.getLazyConfigurationProvider(entry.getRemappedConfiguration()).configure(remappedConfig -> {
Configuration sourceConfig = project.getConfigurations().getByName(entry.getSourceConfiguration()); Configuration sourceConfig = project.getConfigurations().getByName(entry.sourceConfiguration());
Configuration regularConfig = project.getConfigurations().getByName(entry.getTargetConfiguration(project.getConfigurations())); Configuration regularConfig = project.getConfigurations().getByName(entry.getTargetConfiguration(project.getConfigurations()));
List<ModDependencyInfo> modDependencies = new ArrayList<>(); List<ModDependencyInfo> modDependencies = new ArrayList<>();
@ -149,8 +149,8 @@ public class ModCompileRemapper {
Dependency dep = dependencies.module(artifact.getModuleVersion().toString() Dependency dep = dependencies.module(artifact.getModuleVersion().toString()
+ (artifact.getClassifier() == null ? "" : ':' + artifact.getClassifier())); // the owning module of the artifact + (artifact.getClassifier() == null ? "" : ':' + artifact.getClassifier())); // the owning module of the artifact
if (dep instanceof ModuleDependency) { if (dep instanceof ModuleDependency moduleDependency) {
((ModuleDependency) dep).setTransitive(false); moduleDependency.setTransitive(false);
} }
dependencies.add(regularCompile.getName(), dep); dependencies.add(regularCompile.getName(), dep);

View File

@ -71,7 +71,7 @@ public abstract class AnnotationProcessorInvoker<T extends Task> {
private void passMixinArguments(T task) { private void passMixinArguments(T task) {
try { try {
LoomGradleExtension extension = project.getExtensions().getByType(LoomGradleExtension.class); LoomGradleExtension extension = project.getExtensions().getByType(LoomGradleExtension.class);
Map<String, String> args = new HashMap<String, String>() {{ Map<String, String> args = new HashMap<>() {{
put(Constants.MixinArguments.IN_MAP_FILE_NAMED_INTERMEDIARY, extension.getMappingsProvider().tinyMappings.getCanonicalPath()); put(Constants.MixinArguments.IN_MAP_FILE_NAMED_INTERMEDIARY, extension.getMappingsProvider().tinyMappings.getCanonicalPath());
put(Constants.MixinArguments.OUT_MAP_FILE_NAMED_INTERMEDIARY, extension.getNextMixinMappings().getCanonicalPath()); put(Constants.MixinArguments.OUT_MAP_FILE_NAMED_INTERMEDIARY, extension.getNextMixinMappings().getCanonicalPath());
put(Constants.MixinArguments.OUT_REFMAP_FILE, getRefmapDestination(task, extension)); put(Constants.MixinArguments.OUT_REFMAP_FILE, getRefmapDestination(task, extension));

View File

@ -29,13 +29,7 @@ import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class MergedNestedJarProvider implements NestedJarProvider { public record MergedNestedJarProvider(NestedJarProvider... parents) implements NestedJarProvider {
private final NestedJarProvider[] parents;
public MergedNestedJarProvider(NestedJarProvider... parents) {
this.parents = parents;
}
@Override @Override
public Collection<File> provide() { public Collection<File> provide() {
return Arrays.stream(parents) return Arrays.stream(parents)

View File

@ -80,13 +80,12 @@ public final class NestedDependencyProvider implements NestedJarProvider {
DependencySet dependencies = configuration.getDependencies(); DependencySet dependencies = configuration.getDependencies();
for (Dependency dependency : dependencies) { for (Dependency dependency : dependencies) {
if (dependency instanceof ProjectDependency) { if (dependency instanceof ProjectDependency projectDependency) {
ProjectDependency projectDependency = (ProjectDependency) dependency;
Project dependencyProject = projectDependency.getDependencyProject(); Project dependencyProject = projectDependency.getDependencyProject();
for (Task task : dependencyProject.getTasksByName("remapJar", false)) { for (Task task : dependencyProject.getTasksByName("remapJar", false)) {
if (task instanceof RemapJarTask) { if (task instanceof RemapJarTask remapJarTask) {
remapTasks.add((RemapJarTask) task); remapTasks.add(remapJarTask);
} }
} }
} }
@ -99,8 +98,7 @@ public final class NestedDependencyProvider implements NestedJarProvider {
List<DependencyInfo<ProjectDependency>> fileList = new ArrayList<>(); List<DependencyInfo<ProjectDependency>> fileList = new ArrayList<>();
for (Dependency dependency : configuration.getDependencies()) { for (Dependency dependency : configuration.getDependencies()) {
if (dependency instanceof ProjectDependency) { if (dependency instanceof ProjectDependency projectDependency) {
ProjectDependency projectDependency = (ProjectDependency) dependency;
Project dependencyProject = projectDependency.getDependencyProject(); Project dependencyProject = projectDependency.getDependencyProject();
visited.add(dependency.getGroup() + ":" + dependency.getName() + ":" + dependency.getVersion()); visited.add(dependency.getGroup() + ":" + dependency.getName() + ":" + dependency.getVersion());
@ -110,11 +108,11 @@ public final class NestedDependencyProvider implements NestedJarProvider {
Collection<Task> jarTasks = dependencyProject.getTasksByName("jar", false); Collection<Task> jarTasks = dependencyProject.getTasksByName("jar", false);
for (Task task : remapJarTasks.isEmpty() ? jarTasks : remapJarTasks) { for (Task task : remapJarTasks.isEmpty() ? jarTasks : remapJarTasks) {
if (task instanceof RemapJarTask) { if (task instanceof RemapJarTask remapJarTask) {
File file = ((RemapJarTask) task).getArchivePath(); File file = remapJarTask.getArchiveFile().get().getAsFile();
fileList.add(new DependencyInfo<>(projectDependency, new ProjectDependencyMetaExtractor(), file)); fileList.add(new DependencyInfo<>(projectDependency, new ProjectDependencyMetaExtractor(), file));
} else if (task instanceof AbstractArchiveTask) { } else if (task instanceof AbstractArchiveTask abstractArchiveTask) {
File file = ((AbstractArchiveTask) task).getArchivePath(); File file = abstractArchiveTask.getArchiveFile().get().getAsFile();
fileList.add(new DependencyInfo<>(projectDependency, new ProjectDependencyMetaExtractor(), file)); fileList.add(new DependencyInfo<>(projectDependency, new ProjectDependencyMetaExtractor(), file));
} }
} }
@ -208,17 +206,7 @@ public final class NestedDependencyProvider implements NestedJarProvider {
return LoomGradlePlugin.GSON.toJson(jsonObject); return LoomGradlePlugin.GSON.toJson(jsonObject);
} }
private static class DependencyInfo<D> { private record DependencyInfo<D>(D dependency, DependencyMetaExtractor<D> metaExtractor, File file) {
final D dependency;
final DependencyMetaExtractor<D> metaExtractor;
final File file;
DependencyInfo(D dependency, DependencyMetaExtractor<D> metaExtractor, File file) {
this.dependency = dependency;
this.metaExtractor = metaExtractor;
this.file = file;
}
public void validateInputs() { public void validateInputs() {
if (!file.exists()) { if (!file.exists()) {
throw new RuntimeException("Failed to include nested jars, as it could not be found @ " + file.getAbsolutePath()); throw new RuntimeException("Failed to include nested jars, as it could not be found @ " + file.getAbsolutePath());

View File

@ -67,7 +67,7 @@ public final class CompileConfiguration {
data.createLazyConfiguration(Constants.Configurations.UNPICK_CLASSPATH); data.createLazyConfiguration(Constants.Configurations.UNPICK_CLASSPATH);
for (RemappedConfigurationEntry entry : Constants.MOD_COMPILE_ENTRIES) { for (RemappedConfigurationEntry entry : Constants.MOD_COMPILE_ENTRIES) {
data.createLazyConfiguration(entry.getSourceConfiguration()) data.createLazyConfiguration(entry.sourceConfiguration())
.configure(configuration -> configuration.setTransitive(true)); .configure(configuration -> configuration.setTransitive(true));
// Don't get transitive deps of already remapped mods // Don't get transitive deps of already remapped mods
@ -77,7 +77,7 @@ public final class CompileConfiguration {
extendsFrom(entry.getTargetConfiguration(configurations), entry.getRemappedConfiguration(), project); extendsFrom(entry.getTargetConfiguration(configurations), entry.getRemappedConfiguration(), project);
if (entry.isOnModCompileClasspath()) { if (entry.isOnModCompileClasspath()) {
extendsFrom(Constants.Configurations.MOD_COMPILE_CLASSPATH, entry.getSourceConfiguration(), project); extendsFrom(Constants.Configurations.MOD_COMPILE_CLASSPATH, entry.sourceConfiguration(), project);
extendsFrom(Constants.Configurations.MOD_COMPILE_CLASSPATH_MAPPED, entry.getRemappedConfiguration(), project); extendsFrom(Constants.Configurations.MOD_COMPILE_CLASSPATH_MAPPED, entry.getRemappedConfiguration(), project);
} }
} }

View File

@ -100,8 +100,8 @@ public abstract class DependencyProvider {
private String resolvedVersion = null; private String resolvedVersion = null;
public static DependencyInfo create(Project project, Dependency dependency, Configuration sourceConfiguration) { public static DependencyInfo create(Project project, Dependency dependency, Configuration sourceConfiguration) {
if (dependency instanceof SelfResolvingDependency) { if (dependency instanceof SelfResolvingDependency selfResolvingDependency) {
return new FileDependencyInfo(project, (SelfResolvingDependency) dependency, sourceConfiguration); return new FileDependencyInfo(project, selfResolvingDependency, sourceConfiguration);
} else { } else {
return new DependencyInfo(project, dependency, sourceConfiguration); return new DependencyInfo(project, dependency, sourceConfiguration);
} }
@ -138,8 +138,8 @@ public abstract class DependencyProvider {
} }
public Set<File> resolve() { public Set<File> resolve() {
if (dependency instanceof SelfResolvingDependency) { if (dependency instanceof SelfResolvingDependency selfResolvingDependency) {
return ((SelfResolvingDependency) dependency).resolve(); return selfResolvingDependency.resolve();
} }
return sourceConfiguration.files(dependency); return sourceConfiguration.files(dependency);
@ -189,14 +189,11 @@ public abstract class DependencyProvider {
Set<File> files = dependency.resolve(); Set<File> files = dependency.resolve();
this.resolvedFiles = files; this.resolvedFiles = files;
switch (files.size()) { switch (files.size()) {
case 0: //Don't think Gradle would ever let you do this case 0 -> //Don't think Gradle would ever let you do this
throw new IllegalStateException("Empty dependency?"); throw new IllegalStateException("Empty dependency?");
case 1 -> //Single file dependency
case 1: //Single file dependency classifierToFile.put("", Iterables.getOnlyElement(files));
classifierToFile.put("", Iterables.getOnlyElement(files)); default -> { //File collection, try work out the classifiers
break;
default: //File collection, try work out the classifiers
List<File> sortedFiles = files.stream().sorted(Comparator.comparing(File::getName, Comparator.comparingInt(String::length))).collect(Collectors.toList()); List<File> sortedFiles = files.stream().sorted(Comparator.comparing(File::getName, Comparator.comparingInt(String::length))).collect(Collectors.toList());
//First element in sortedFiles is the one with the shortest name, we presume all the others are different classifier types of this //First element in sortedFiles is the one with the shortest name, we presume all the others are different classifier types of this
File shortest = sortedFiles.remove(0); File shortest = sortedFiles.remove(0);
@ -223,6 +220,7 @@ public abstract class DependencyProvider {
} }
} }
} }
}
if (dependency.getGroup() != null && dependency.getVersion() != null) { if (dependency.getGroup() != null && dependency.getVersion() != null) {
group = dependency.getGroup(); group = dependency.getGroup();

View File

@ -51,7 +51,7 @@ public final class MavenPublication {
continue; continue;
} }
Configuration compileModsConfig = p.getConfigurations().getByName(entry.getSourceConfiguration()); Configuration compileModsConfig = p.getConfigurations().getByName(entry.sourceConfiguration());
// add modsCompile to maven-publish // add modsCompile to maven-publish
PublishingExtension mavenPublish = p.getExtensions().findByType(PublishingExtension.class); PublishingExtension mavenPublish = p.getExtensions().findByType(PublishingExtension.class);
@ -92,7 +92,7 @@ public final class MavenPublication {
depNode.appendNode("groupId", dependency.getGroup()); depNode.appendNode("groupId", dependency.getGroup());
depNode.appendNode("artifactId", dependency.getName()); depNode.appendNode("artifactId", dependency.getName());
depNode.appendNode("version", dependency.getVersion()); depNode.appendNode("version", dependency.getVersion());
depNode.appendNode("scope", entry.getMavenScope()); depNode.appendNode("scope", entry.mavenScope());
if (!(dependency instanceof ModuleDependency)) { if (!(dependency instanceof ModuleDependency)) {
continue; continue;

View File

@ -27,35 +27,11 @@ package net.fabricmc.loom.configuration;
import org.gradle.api.artifacts.ConfigurationContainer; import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.plugins.JavaPlugin;
public class RemappedConfigurationEntry { public record RemappedConfigurationEntry(String sourceConfiguration, String targetConfiguration, boolean isOnModCompileClasspath, String mavenScope) {
private final String sourceConfiguration;
private final String targetConfiguration;
private final String mavenScope;
private final boolean isOnModCompileClasspath;
public RemappedConfigurationEntry(String sourceConfiguration, String targetConfiguration, boolean isOnModCompileClasspath, String mavenScope) {
this.sourceConfiguration = sourceConfiguration;
this.targetConfiguration = targetConfiguration;
this.isOnModCompileClasspath = isOnModCompileClasspath;
this.mavenScope = mavenScope;
}
public String getMavenScope() {
return mavenScope;
}
public boolean hasMavenScope() { public boolean hasMavenScope() {
return mavenScope != null && !mavenScope.isEmpty(); return mavenScope != null && !mavenScope.isEmpty();
} }
public boolean isOnModCompileClasspath() {
return isOnModCompileClasspath;
}
public String getSourceConfiguration() {
return sourceConfiguration;
}
public String getRemappedConfiguration() { public String getRemappedConfiguration() {
return sourceConfiguration + "Mapped"; return sourceConfiguration + "Mapped";
} }

View File

@ -36,7 +36,6 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import org.apache.commons.io.IOUtils;
import org.gradle.api.Project; import org.gradle.api.Project;
import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.SourceSet;
import org.gradle.plugins.ide.eclipse.model.EclipseModel; import org.gradle.plugins.ide.eclipse.model.EclipseModel;
@ -222,7 +221,7 @@ public class RunConfig {
String dummyConfig; String dummyConfig;
try (InputStream input = SetupIntelijRunConfigs.class.getClassLoader().getResourceAsStream(dummy)) { try (InputStream input = SetupIntelijRunConfigs.class.getClassLoader().getResourceAsStream(dummy)) {
dummyConfig = IOUtils.toString(input, StandardCharsets.UTF_8); dummyConfig = new String(input.readAllBytes(), StandardCharsets.UTF_8);
} }
dummyConfig = dummyConfig.replace("%NAME%", configName); dummyConfig = dummyConfig.replace("%NAME%", configName);

View File

@ -42,7 +42,6 @@ import java.util.stream.Collectors;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import org.apache.commons.io.IOUtils;
import org.gradle.api.Project; import org.gradle.api.Project;
import org.objectweb.asm.commons.Remapper; import org.objectweb.asm.commons.Remapper;
import org.zeroturnaround.zip.ZipUtil; import org.zeroturnaround.zip.ZipUtil;
@ -156,7 +155,7 @@ public class ModProcessor {
final Map<ModDependencyInfo, byte[]> accessWidenerMap = new HashMap<>(); final Map<ModDependencyInfo, byte[]> accessWidenerMap = new HashMap<>();
for (RemappedConfigurationEntry entry : Constants.MOD_COMPILE_ENTRIES) { for (RemappedConfigurationEntry entry : Constants.MOD_COMPILE_ENTRIES) {
for (File inputFile : project.getConfigurations().getByName(entry.getSourceConfiguration()).getFiles()) { for (File inputFile : project.getConfigurations().getByName(entry.sourceConfiguration()).getFiles()) {
if (remapList.stream().noneMatch(info -> info.getInputFile().equals(inputFile))) { if (remapList.stream().noneMatch(info -> info.getInputFile().equals(inputFile))) {
project.getLogger().debug("Adding " + inputFile + " onto the remap classpath"); project.getLogger().debug("Adding " + inputFile + " onto the remap classpath");
@ -229,7 +228,7 @@ public class ModProcessor {
} }
try (InputStream inputstream = jarFile.getInputStream(entry)) { try (InputStream inputstream = jarFile.getInputStream(entry)) {
jsonStr = IOUtils.toString(inputstream, StandardCharsets.UTF_8); jsonStr = new String(inputstream.readAllBytes(), StandardCharsets.UTF_8);
} }
} }

View File

@ -34,7 +34,6 @@ import java.util.jar.JarFile;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.Configuration;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -80,7 +79,7 @@ public class ModDependencyInfo {
} }
public File getRemappedDir() { public File getRemappedDir() {
return new File(remapData.modStore, String.format("%s/%s/%s", getGroup().replace(".", "/"), name, version)); return new File(remapData.modStore(), String.format("%s/%s/%s", getGroup().replace(".", "/"), name, version));
} }
public File getRemappedOutput() { public File getRemappedOutput() {
@ -96,7 +95,7 @@ public class ModDependencyInfo {
} }
private String getGroup() { private String getGroup() {
return getMappingsPrefix(remapData.mappingsSuffix) + "." + group; return getMappingsPrefix(remapData.mappingsSuffix()) + "." + group;
} }
public static String getMappingsPrefix(String mappings) { public static String getMappingsPrefix(String mappings) {
@ -121,7 +120,7 @@ public class ModDependencyInfo {
String pomTemplate; String pomTemplate;
try (InputStream input = ModDependencyInfo.class.getClassLoader().getResourceAsStream("mod_compile_template.pom")) { try (InputStream input = ModDependencyInfo.class.getClassLoader().getResourceAsStream("mod_compile_template.pom")) {
pomTemplate = IOUtils.toString(input, StandardCharsets.UTF_8); pomTemplate = new String(input.readAllBytes(), StandardCharsets.UTF_8);
} }
pomTemplate = pomTemplate pomTemplate = pomTemplate

View File

@ -26,12 +26,5 @@ package net.fabricmc.loom.configuration.processors.dependency;
import java.io.File; import java.io.File;
public class RemapData { public record RemapData(String mappingsSuffix, File modStore) {
public final String mappingsSuffix;
public final File modStore;
public RemapData(String mappingsSuffix, File modStore) {
this.mappingsSuffix = mappingsSuffix;
this.modStore = modStore;
}
} }

View File

@ -65,7 +65,7 @@ public class LaunchProvider extends DependencyProvider {
.property("client", "org.lwjgl.librarypath", getExtension().getNativesDirectory().getAbsolutePath()) .property("client", "org.lwjgl.librarypath", getExtension().getNativesDirectory().getAbsolutePath())
.argument("client", "--assetIndex") .argument("client", "--assetIndex")
.argument("client", getExtension().getMinecraftProvider().getVersionInfo().getAssetIndex().getFabricId(getExtension().getMinecraftProvider().getMinecraftVersion())) .argument("client", getExtension().getMinecraftProvider().getVersionInfo().assetIndex().fabricId(getExtension().getMinecraftProvider().getMinecraftVersion()))
.argument("client", "--assetsDir") .argument("client", "--assetsDir")
.argument("client", new File(getExtension().getUserCache(), "assets").getAbsolutePath()); .argument("client", new File(getExtension().getUserCache(), "assets").getAbsolutePath());
@ -112,7 +112,7 @@ public class LaunchProvider extends DependencyProvider {
private void writeRemapClassPath() { private void writeRemapClassPath() {
List<String> inputConfigurations = new ArrayList<>(); List<String> inputConfigurations = new ArrayList<>();
inputConfigurations.add(Constants.Configurations.LOADER_DEPENDENCIES); inputConfigurations.add(Constants.Configurations.LOADER_DEPENDENCIES);
inputConfigurations.addAll(Constants.MOD_COMPILE_ENTRIES.stream().map(RemappedConfigurationEntry::getSourceConfiguration).collect(Collectors.toList())); inputConfigurations.addAll(Constants.MOD_COMPILE_ENTRIES.stream().map(RemappedConfigurationEntry::sourceConfiguration).collect(Collectors.toList()));
List<File> remapClasspath = new ArrayList<>(); List<File> remapClasspath = new ArrayList<>();
@ -127,7 +127,7 @@ public class LaunchProvider extends DependencyProvider {
.collect(Collectors.joining(File.pathSeparator)); .collect(Collectors.joining(File.pathSeparator));
try { try {
Files.write(getRemapClasspathFile().toPath(), str.getBytes(StandardCharsets.UTF_8)); Files.writeString(getRemapClasspathFile().toPath(), str);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to generate remap classpath", e); throw new RuntimeException("Failed to generate remap classpath", e);
} }

View File

@ -33,7 +33,6 @@ import java.util.Optional;
import java.util.function.Consumer; import java.util.function.Consumer;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.google.gson.GsonBuilder;
import org.gradle.api.GradleException; import org.gradle.api.GradleException;
import org.gradle.api.Project; import org.gradle.api.Project;
import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logger;
@ -75,7 +74,7 @@ public class MinecraftProvider extends DependencyProvider {
downloadMcJson(offline); downloadMcJson(offline);
try (FileReader reader = new FileReader(minecraftJson)) { try (FileReader reader = new FileReader(minecraftJson)) {
versionInfo = LoomGradlePlugin.GSON.fromJson(reader, MinecraftVersionMeta.class); versionInfo = LoomGradlePlugin.OBJECT_MAPPER.readValue(reader, MinecraftVersionMeta.class);
} }
// Add Loom as an annotation processor // Add Loom as an annotation processor
@ -140,7 +139,7 @@ public class MinecraftProvider extends DependencyProvider {
} }
String versionManifest = Files.asCharSource(versionManifestJson, StandardCharsets.UTF_8).read(); String versionManifest = Files.asCharSource(versionManifestJson, StandardCharsets.UTF_8).read();
ManifestVersion mcManifest = new GsonBuilder().create().fromJson(versionManifest, ManifestVersion.class); ManifestVersion mcManifest = LoomGradlePlugin.OBJECT_MAPPER.readValue(versionManifest, ManifestVersion.class);
Optional<ManifestVersion.Versions> optionalVersion = Optional.empty(); Optional<ManifestVersion.Versions> optionalVersion = Optional.empty();
@ -153,7 +152,7 @@ public class MinecraftProvider extends DependencyProvider {
} }
if (!optionalVersion.isPresent()) { if (!optionalVersion.isPresent()) {
optionalVersion = mcManifest.versions.stream().filter(versions -> versions.id.equalsIgnoreCase(minecraftVersion)).findFirst(); optionalVersion = mcManifest.versions().stream().filter(versions -> versions.id.equalsIgnoreCase(minecraftVersion)).findFirst();
} }
if (optionalVersion.isPresent()) { if (optionalVersion.isPresent()) {
@ -197,8 +196,8 @@ public class MinecraftProvider extends DependencyProvider {
return false; return false;
} }
ManifestVersion manifest = new GsonBuilder().create().fromJson(Files.asCharSource(versionManifestJson, StandardCharsets.UTF_8).read(), ManifestVersion.class); ManifestVersion manifest = LoomGradlePlugin.OBJECT_MAPPER.readValue(Files.asCharSource(versionManifestJson, StandardCharsets.UTF_8).read(), ManifestVersion.class);
Optional<ManifestVersion.Versions> version = manifest.versions.stream().filter(versions -> versions.id.equalsIgnoreCase(minecraftVersion)).findFirst(); Optional<ManifestVersion.Versions> version = manifest.versions().stream().filter(versions -> versions.id.equalsIgnoreCase(minecraftVersion)).findFirst();
// fail if the expected mc version was not found, will download the file again. // fail if the expected mc version was not found, will download the file again.
return version.isPresent(); return version.isPresent();
@ -209,11 +208,11 @@ public class MinecraftProvider extends DependencyProvider {
return; return;
} }
MinecraftVersionMeta.Download client = versionInfo.getDownload("client"); MinecraftVersionMeta.Download client = versionInfo.download("client");
MinecraftVersionMeta.Download server = versionInfo.getDownload("server"); MinecraftVersionMeta.Download server = versionInfo.download("server");
HashedDownloadUtil.downloadIfInvalid(new URL(client.getUrl()), minecraftClientJar, client.getSha1(), logger, false); HashedDownloadUtil.downloadIfInvalid(new URL(client.url()), minecraftClientJar, client.sha1(), logger, false);
HashedDownloadUtil.downloadIfInvalid(new URL(server.getUrl()), minecraftServerJar, server.getSha1(), logger, false); HashedDownloadUtil.downloadIfInvalid(new URL(server.url()), minecraftServerJar, server.sha1(), logger, false);
} }
private void mergeJars(Logger logger) throws IOException { private void mergeJars(Logger logger) throws IOException {

View File

@ -28,7 +28,6 @@ import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem; import java.nio.file.FileSystem;
import java.nio.file.FileSystems; import java.nio.file.FileSystems;
import java.nio.file.Files; import java.nio.file.Files;
@ -259,7 +258,7 @@ public class MappingsProvider extends DependencyProvider {
} }
private UnpickMetadata parseUnpickMetadata(Path input) throws IOException { private UnpickMetadata parseUnpickMetadata(Path input) throws IOException {
JsonObject jsonObject = LoomGradlePlugin.GSON.fromJson(new String(Files.readAllBytes(input), StandardCharsets.UTF_8), JsonObject.class); JsonObject jsonObject = LoomGradlePlugin.GSON.fromJson(Files.readString(input), JsonObject.class);
if (!jsonObject.has("version") || jsonObject.get("version").getAsInt() != 1) { if (!jsonObject.has("version") || jsonObject.get("version").getAsInt() != 1) {
throw new UnsupportedOperationException("Unsupported unpick version"); throw new UnsupportedOperationException("Unsupported unpick version");
@ -409,13 +408,6 @@ public class MappingsProvider extends DependencyProvider {
return hasUnpickDefinitions; return hasUnpickDefinitions;
} }
public static class UnpickMetadata { public record UnpickMetadata(String unpickGroup, String unpickVersion) {
public final String unpickGroup;
public final String unpickVersion;
public UnpickMetadata(String unpickGroup, String unpickVersion) {
this.unpickGroup = unpickGroup;
this.unpickVersion = unpickVersion;
}
} }
} }

View File

@ -123,15 +123,15 @@ public class MojangMappingsDependency implements SelfResolvingDependency {
private MappingSet getMappingsSet(Path clientMappings, Path serverMappings) throws IOException { private MappingSet getMappingsSet(Path clientMappings, Path serverMappings) throws IOException {
MinecraftVersionMeta versionInfo = extension.getMinecraftProvider().getVersionInfo(); MinecraftVersionMeta versionInfo = extension.getMinecraftProvider().getVersionInfo();
if (versionInfo.getDownload(MANIFEST_CLIENT_MAPPINGS) == null) { if (versionInfo.download(MANIFEST_CLIENT_MAPPINGS) == null) {
throw new RuntimeException("Failed to find official mojang mappings for " + getVersion()); throw new RuntimeException("Failed to find official mojang mappings for " + getVersion());
} }
MinecraftVersionMeta.Download clientMappingsDownload = versionInfo.getDownload(MANIFEST_CLIENT_MAPPINGS); MinecraftVersionMeta.Download clientMappingsDownload = versionInfo.download(MANIFEST_CLIENT_MAPPINGS);
MinecraftVersionMeta.Download serverMappingsDownload = versionInfo.getDownload(MANIFEST_CLIENT_MAPPINGS); MinecraftVersionMeta.Download serverMappingsDownload = versionInfo.download(MANIFEST_CLIENT_MAPPINGS);
HashedDownloadUtil.downloadIfInvalid(new URL(clientMappingsDownload.getUrl()), clientMappings.toFile(), clientMappingsDownload.getSha1(), project.getLogger(), false); HashedDownloadUtil.downloadIfInvalid(new URL(clientMappingsDownload.url()), clientMappings.toFile(), clientMappingsDownload.sha1(), project.getLogger(), false);
HashedDownloadUtil.downloadIfInvalid(new URL(serverMappingsDownload.getUrl()), serverMappings.toFile(), clientMappingsDownload.getSha1(), project.getLogger(), false); HashedDownloadUtil.downloadIfInvalid(new URL(serverMappingsDownload.url()), serverMappings.toFile(), clientMappingsDownload.sha1(), project.getLogger(), false);
MappingSet mappings = MappingSet.create(); MappingSet mappings = MappingSet.create();
@ -208,8 +208,8 @@ public class MojangMappingsDependency implements SelfResolvingDependency {
@Override @Override
public boolean contentEquals(Dependency dependency) { public boolean contentEquals(Dependency dependency) {
if (dependency instanceof MojangMappingsDependency) { if (dependency instanceof MojangMappingsDependency mojangMappingsDependency) {
return ((MojangMappingsDependency) dependency).extension.getMinecraftProvider().getMinecraftVersion().equals(getVersion()); return mojangMappingsDependency.extension.getMinecraftProvider().getMinecraftVersion().equals(getVersion());
} }
return false; return false;

View File

@ -24,12 +24,10 @@
package net.fabricmc.loom.configuration.providers.minecraft; package net.fabricmc.loom.configuration.providers.minecraft;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
public class ManifestVersion { public record ManifestVersion(List<Versions> versions, Map<String, String> latest) {
public List<Versions> versions = new ArrayList<>();
public static class Versions { public static class Versions {
public String id, url, sha1; public String id, url, sha1;
} }

View File

@ -40,9 +40,9 @@ public class MinecraftLibraryProvider {
initFiles(project, minecraftProvider); initFiles(project, minecraftProvider);
for (MinecraftVersionMeta.Library library : versionInfo.getLibraries()) { for (MinecraftVersionMeta.Library library : versionInfo.libraries()) {
if (library.isValidForOS() && !library.hasNatives() && library.getArtifact() != null) { if (library.isValidForOS() && !library.hasNatives() && library.artifact() != null) {
project.getDependencies().add(Constants.Configurations.MINECRAFT_DEPENDENCIES, project.getDependencies().module(library.getName())); project.getDependencies().add(Constants.Configurations.MINECRAFT_DEPENDENCIES, project.getDependencies().module(library.name()));
} }
} }
} }

View File

@ -89,11 +89,11 @@ public class MinecraftNativesProvider {
nativesDir.mkdirs(); nativesDir.mkdirs();
for (MinecraftVersionMeta.Classifier library : getNatives()) { for (MinecraftVersionMeta.Download library : getNatives()) {
File libJarFile = library.getRelativeFile(jarStore); File libJarFile = library.relativeFile(jarStore);
if (!offline) { if (!offline) {
HashedDownloadUtil.downloadIfInvalid(new URL(library.getUrl()), libJarFile, library.getSha1(), project.getLogger(), false); HashedDownloadUtil.downloadIfInvalid(new URL(library.url()), libJarFile, library.sha1(), project.getLogger(), false);
} }
if (!libJarFile.exists()) { if (!libJarFile.exists()) {
@ -104,19 +104,19 @@ public class MinecraftNativesProvider {
// Store a file containing the hash of the extracted natives, used on subsequent runs to skip extracting all the natives if they haven't changed // Store a file containing the hash of the extracted natives, used on subsequent runs to skip extracting all the natives if they haven't changed
File libSha1File = new File(nativesDir, libJarFile.getName() + ".sha1"); File libSha1File = new File(nativesDir, libJarFile.getName() + ".sha1");
FileUtils.writeStringToFile(libSha1File, library.getSha1(), StandardCharsets.UTF_8); FileUtils.writeStringToFile(libSha1File, library.sha1(), StandardCharsets.UTF_8);
} }
} }
private boolean requiresExtract() { private boolean requiresExtract() {
List<MinecraftVersionMeta.Classifier> natives = getNatives(); List<MinecraftVersionMeta.Download> natives = getNatives();
if (natives.isEmpty()) { if (natives.isEmpty()) {
throw new IllegalStateException("No natives found for the current system"); throw new IllegalStateException("No natives found for the current system");
} }
for (MinecraftVersionMeta.Classifier library : natives) { for (MinecraftVersionMeta.Download library : natives) {
File libJarFile = library.getRelativeFile(jarStore); File libJarFile = library.relativeFile(jarStore);
File libSha1File = new File(nativesDir, libJarFile.getName() + ".sha1"); File libSha1File = new File(nativesDir, libJarFile.getName() + ".sha1");
if (!libSha1File.exists()) { if (!libSha1File.exists()) {
@ -126,7 +126,7 @@ public class MinecraftNativesProvider {
try { try {
String sha1 = FileUtils.readFileToString(libSha1File, StandardCharsets.UTF_8); String sha1 = FileUtils.readFileToString(libSha1File, StandardCharsets.UTF_8);
if (!sha1.equalsIgnoreCase(library.getSha1())) { if (!sha1.equalsIgnoreCase(library.sha1())) {
return true; return true;
} }
} catch (IOException e) { } catch (IOException e) {
@ -139,10 +139,10 @@ public class MinecraftNativesProvider {
return false; return false;
} }
private List<MinecraftVersionMeta.Classifier> getNatives() { private List<MinecraftVersionMeta.Download> getNatives() {
return extension.getMinecraftProvider().getVersionInfo().getLibraries().stream() return extension.getMinecraftProvider().getVersionInfo().libraries().stream()
.filter((MinecraftVersionMeta.Library::hasNativesForOS)) .filter((MinecraftVersionMeta.Library::hasNativesForOS))
.map(MinecraftVersionMeta.Library::getClassifierForOS) .map(MinecraftVersionMeta.Library::classifierForOS)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }

View File

@ -29,108 +29,35 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import com.google.gson.JsonObject;
import net.fabricmc.loom.util.OperatingSystem; import net.fabricmc.loom.util.OperatingSystem;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class MinecraftVersionMeta { public record MinecraftVersionMeta(
private JsonObject arguments; Object arguments,
private AssetIndex assetIndex; AssetIndex assetIndex,
private String assets; String assets,
private int complianceLevel; int complianceLevel,
private Map<String, Download> downloads; Map<String, Download> downloads,
private String id; String id,
private List<Library> libraries; List<Library> libraries,
private JsonObject logging; Object logging,
private String mainClass; String mainClass,
private int minimumLauncherVersion; int minimumLauncherVersion,
private String releaseTime; String releaseTime,
private String time; String time,
private String type; String type
) {
public Download getDownload(String key) { public Download download(String key) {
return getDownloads().get(key); return downloads().get(key);
} }
public JsonObject getArguments() { public record AssetIndex(String id, long totalSize, String path, String sha1, long size, String url) {
return arguments; public String fabricId(String version) {
}
public AssetIndex getAssetIndex() {
return assetIndex;
}
public String getAssets() {
return assets;
}
public int getComplianceLevel() {
return complianceLevel;
}
public Map<String, Download> getDownloads() {
return downloads;
}
public String getId() {
return id;
}
public List<Library> getLibraries() {
return libraries;
}
public JsonObject getLogging() {
return logging;
}
public String getMainClass() {
return mainClass;
}
public int getMinimumLauncherVersion() {
return minimumLauncherVersion;
}
public String getReleaseTime() {
return releaseTime;
}
public String getTime() {
return time;
}
public String getType() {
return type;
}
public final class AssetIndex extends Downloadable {
private String id;
private long totalSize;
public String getFabricId(String version) {
return id.equals(version) ? version : version + "-" + id; return id.equals(version) ? version : version + "-" + id;
} }
public String getId() {
return id;
}
public long getTotalSize() {
return totalSize;
}
} }
public final class Download extends Downloadable { public record Library(Downloads downloads, String name, Map<String, String> natives, List<Rule> rules, Object extract) {
}
public final class Library {
private Downloads downloads;
private String name;
private Map<String, String> natives;
private List<Rule> rules;
public boolean isValidForOS() { public boolean isValidForOS() {
if (rules == null || rules.isEmpty()) { if (rules == null || rules.isEmpty()) {
return true; return true;
@ -161,117 +88,45 @@ public final class MinecraftVersionMeta {
return isValidForOS(); return isValidForOS();
} }
public Classifier getClassifierForOS() { public Download classifierForOS() {
return getDownloads().getClassifier(natives.get(OperatingSystem.getOS())); return downloads().classifier(natives.get(OperatingSystem.getOS()));
} }
public Downloads getDownloads() { public Download artifact() {
return downloads; if (downloads() == null) {
}
public Artifact getArtifact() {
if (getDownloads() == null) {
return null; return null;
} }
return getDownloads().getArtifact(); return downloads().artifact();
}
public String getName() {
return name;
}
public Map<String, String> getNatives() {
return natives;
}
public List<Rule> getRules() {
return rules;
} }
} }
public final class Downloads { public record Downloads(Download artifact, Map<String, Download> classifiers) {
private Artifact artifact; public Download classifier(String os) {
private Map<String, Classifier> classifiers;
public Classifier getClassifier(String os) {
return classifiers.get(os); return classifiers.get(os);
} }
public Artifact getArtifact() {
return artifact;
}
public Map<String, Classifier> getClassifiers() {
return classifiers;
}
} }
public final class Artifact extends Downloadable { public record Rule(String action, OS os) {
}
public final class Classifier extends Downloadable {
}
public final class Rule {
private String action;
private OS os;
public boolean appliesToOS() { public boolean appliesToOS() {
return getOS() == null || getOS().isValidForOS(); return os() == null || os().isValidForOS();
} }
public boolean isAllowed() { public boolean isAllowed() {
return getAction().equals("allow"); return action().equals("allow");
}
public String getAction() {
return action;
}
public OS getOS() {
return os;
} }
} }
public final class OS { public record OS(String name) {
private String name;
public boolean isValidForOS() { public boolean isValidForOS() {
return getName() == null || getName().equalsIgnoreCase(OperatingSystem.getOS()); return name() == null || name().equalsIgnoreCase(OperatingSystem.getOS());
}
public String getName() {
return name;
} }
} }
// A base class for everything that can be downloaded public record Download(String path, String sha1, long size, String url) {
public abstract class Downloadable { public File relativeFile(File baseDirectory) {
private String path; Objects.requireNonNull(path(), "Cannot get relative file from a null path");
private String sha1; return new File(baseDirectory, path());
private long size;
private String url;
public File getRelativeFile(File baseDirectory) {
Objects.requireNonNull(getPath(), "Cannot get relative file from a null path");
return new File(baseDirectory, getPath());
}
public String getPath() {
return path;
}
public String getSha1() {
return sha1;
}
public long getSize() {
return size;
}
public String getUrl() {
return url;
} }
} }
} }

View File

@ -30,23 +30,12 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class AssetIndex { public record AssetIndex(Map<String, AssetObject> objects, boolean virtual) {
private final Map<String, AssetObject> objects;
private boolean virtual;
public AssetIndex() { public AssetIndex() {
this.objects = new LinkedHashMap<>(); this(new LinkedHashMap<>(), false);
}
public Map<String, AssetObject> getFileMap() {
return this.objects;
} }
public Set<AssetObject> getUniqueObjects() { public Set<AssetObject> getUniqueObjects() {
return new HashSet<>(this.objects.values()); return new HashSet<>(this.objects.values());
} }
public boolean isVirtual() {
return this.virtual;
}
} }

View File

@ -25,34 +25,5 @@
package net.fabricmc.loom.configuration.providers.minecraft.assets; package net.fabricmc.loom.configuration.providers.minecraft.assets;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class AssetObject { public record AssetObject(String hash, long size) {
private String hash;
private long size;
public String getHash() {
return this.hash;
}
public long getSize() {
return this.size;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if ((o == null) || (getClass() != o.getClass())) {
return false;
} else {
AssetObject that = (AssetObject) o;
return this.size == that.size && this.hash.equals(that.hash);
}
}
@Override
public int hashCode() {
int result = this.hash.hashCode();
result = 31 * result + (int) (this.size ^ this.size >>> 32);
return result;
}
} }

View File

@ -53,7 +53,7 @@ public class MinecraftAssetsProvider {
boolean offline = project.getGradle().getStartParameter().isOffline(); boolean offline = project.getGradle().getStartParameter().isOffline();
MinecraftVersionMeta versionInfo = minecraftProvider.getVersionInfo(); MinecraftVersionMeta versionInfo = minecraftProvider.getVersionInfo();
MinecraftVersionMeta.AssetIndex assetIndex = versionInfo.getAssetIndex(); MinecraftVersionMeta.AssetIndex assetIndex = versionInfo.assetIndex();
// get existing cache files // get existing cache files
File assets = new File(extension.getUserCache(), "assets"); File assets = new File(extension.getUserCache(), "assets");
@ -62,7 +62,7 @@ public class MinecraftAssetsProvider {
assets.mkdirs(); assets.mkdirs();
} }
File assetsInfo = new File(assets, "indexes" + File.separator + assetIndex.getFabricId(minecraftProvider.getMinecraftVersion()) + ".json"); File assetsInfo = new File(assets, "indexes" + File.separator + assetIndex.fabricId(minecraftProvider.getMinecraftVersion()) + ".json");
project.getLogger().info(":downloading asset index"); project.getLogger().info(":downloading asset index");
@ -75,7 +75,7 @@ public class MinecraftAssetsProvider {
throw new GradleException("Asset index not found at " + assetsInfo.getAbsolutePath()); throw new GradleException("Asset index not found at " + assetsInfo.getAbsolutePath());
} }
} else { } else {
HashedDownloadUtil.downloadIfInvalid(new URL(assetIndex.getUrl()), assetsInfo, assetIndex.getSha1(), project.getLogger(), false); HashedDownloadUtil.downloadIfInvalid(new URL(assetIndex.url()), assetsInfo, assetIndex.sha1(), project.getLogger(), false);
} }
Deque<ProgressLogger> loggers = new ConcurrentLinkedDeque<>(); Deque<ProgressLogger> loggers = new ConcurrentLinkedDeque<>();
@ -84,16 +84,16 @@ public class MinecraftAssetsProvider {
AssetIndex index; AssetIndex index;
try (FileReader fileReader = new FileReader(assetsInfo)) { try (FileReader fileReader = new FileReader(assetsInfo)) {
index = LoomGradlePlugin.GSON.fromJson(fileReader, AssetIndex.class); index = LoomGradlePlugin.OBJECT_MAPPER.readValue(fileReader, AssetIndex.class);
} }
Stopwatch stopwatch = Stopwatch.createStarted(); Stopwatch stopwatch = Stopwatch.createStarted();
Map<String, AssetObject> parent = index.getFileMap(); Map<String, AssetObject> parent = index.objects();
for (Map.Entry<String, AssetObject> entry : parent.entrySet()) { for (Map.Entry<String, AssetObject> entry : parent.entrySet()) {
AssetObject object = entry.getValue(); AssetObject object = entry.getValue();
String sha1 = object.getHash(); String sha1 = object.hash();
String filename = "objects" + File.separator + sha1.substring(0, 2) + File.separator + sha1; String filename = "objects" + File.separator + sha1.substring(0, 2) + File.separator + sha1;
File file = new File(assets, filename); File file = new File(assets, filename);

View File

@ -89,7 +89,7 @@ public class LineNumberRemapper {
} }
public void process(ProgressLogger logger, Path input, Path output) throws IOException { public void process(ProgressLogger logger, Path input, Path output) throws IOException {
Files.walkFileTree(input, new SimpleFileVisitor<Path>() { Files.walkFileTree(input, new SimpleFileVisitor<>() {
@Override @Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String rel = input.relativize(file).toString(); String rel = input.relativize(file).toString();

View File

@ -54,7 +54,6 @@ import java.util.zip.ZipFile;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.io.ByteStreams;
import org.benf.cfr.reader.api.CfrDriver; import org.benf.cfr.reader.api.CfrDriver;
import org.benf.cfr.reader.api.ClassFileSource; import org.benf.cfr.reader.api.ClassFileSource;
import org.benf.cfr.reader.api.OutputSinkFactory; import org.benf.cfr.reader.api.OutputSinkFactory;
@ -134,36 +133,29 @@ public class FabricCFRDecompiler implements LoomDecompiler {
} }
try (InputStream inputStream = inputZip.getInputStream(zipEntry)) { try (InputStream inputStream = inputZip.getInputStream(zipEntry)) {
return Pair.make(ByteStreams.toByteArray(inputStream), path); return Pair.make(inputStream.readAllBytes(), path);
} }
} }
}) })
.withOutputSink(new OutputSinkFactory() { .withOutputSink(new OutputSinkFactory() {
@Override @Override
public List<SinkClass> getSupportedSinks(SinkType sinkType, Collection<SinkClass> available) { public List<SinkClass> getSupportedSinks(SinkType sinkType, Collection<SinkClass> available) {
switch (sinkType) { return switch (sinkType) {
case PROGRESS: case PROGRESS -> Collections.singletonList(SinkClass.STRING);
return Collections.singletonList(SinkClass.STRING); case JAVA -> Collections.singletonList(SinkClass.DECOMPILED);
case JAVA: default -> Collections.emptyList();
return Collections.singletonList(SinkClass.DECOMPILED); };
default:
return Collections.emptyList();
}
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public <T> Sink<T> getSink(SinkType sinkType, SinkClass sinkClass) { public <T> Sink<T> getSink(SinkType sinkType, SinkClass sinkClass) {
switch (sinkType) { return switch (sinkType) {
case PROGRESS: case PROGRESS -> (p) -> project.getLogger().debug((String) p);
return (p) -> project.getLogger().debug((String) p); case JAVA -> (Sink<T>) decompiledSink(jos, addedDirectories);
case JAVA: case EXCEPTION -> (e) -> project.getLogger().error((String) e);
return (Sink<T>) decompiledSink(jos, addedDirectories); default -> null;
case EXCEPTION: };
return (e) -> project.getLogger().error((String) e);
}
return null;
} }
}) })
.build(); .build();
@ -173,7 +165,7 @@ public class FabricCFRDecompiler implements LoomDecompiler {
.filter(input -> input.endsWith(".class")) .filter(input -> input.endsWith(".class"))
.collect(Collectors.toList()); .collect(Collectors.toList());
ExecutorService executorService = Executors.newFixedThreadPool(metaData.numberOfThreads); ExecutorService executorService = Executors.newFixedThreadPool(metaData.numberOfThreads());
List<Future<?>> futures = new LinkedList<>(); List<Future<?>> futures = new LinkedList<>();
for (String clazz : classes) { for (String clazz : classes) {

View File

@ -65,12 +65,12 @@ public abstract class AbstractFernFlowerDecompiler implements LoomDecompiler {
project.getLogging().captureStandardOutput(LogLevel.LIFECYCLE); project.getLogging().captureStandardOutput(LogLevel.LIFECYCLE);
Map<String, Object> options = new HashMap<String, Object>() {{ Map<String, Object> options = new HashMap<>() {{
put(IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES, "1"); put(IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES, "1");
put(IFernflowerPreferences.BYTECODE_SOURCE_MAPPING, "1"); put(IFernflowerPreferences.BYTECODE_SOURCE_MAPPING, "1");
put(IFernflowerPreferences.REMOVE_SYNTHETIC, "1"); put(IFernflowerPreferences.REMOVE_SYNTHETIC, "1");
put(IFernflowerPreferences.LOG_LEVEL, "trace"); put(IFernflowerPreferences.LOG_LEVEL, "trace");
put(IFernflowerPreferences.THREADS, metaData.numberOfThreads); put(IFernflowerPreferences.THREADS, metaData.numberOfThreads());
}}; }};
List<String> args = new ArrayList<>(); List<String> args = new ArrayList<>();
@ -79,10 +79,10 @@ public abstract class AbstractFernFlowerDecompiler implements LoomDecompiler {
args.add(absolutePathOf(compiledJar)); args.add(absolutePathOf(compiledJar));
args.add("-o=" + absolutePathOf(sourcesDestination)); args.add("-o=" + absolutePathOf(sourcesDestination));
args.add("-l=" + absolutePathOf(linemapDestination)); args.add("-l=" + absolutePathOf(linemapDestination));
args.add("-m=" + absolutePathOf(metaData.javaDocs)); args.add("-m=" + absolutePathOf(metaData.javaDocs()));
// TODO, Decompiler breaks on jemalloc, J9 module-info.class? // TODO, Decompiler breaks on jemalloc, J9 module-info.class?
for (Path library : metaData.libraries) { for (Path library : metaData.libraries()) {
args.add("-e=" + absolutePathOf(library)); args.add("-e=" + absolutePathOf(library));
} }

View File

@ -30,13 +30,11 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.gradle.api.Project; import org.gradle.api.Project;
import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.TaskAction;
import net.fabricmc.loom.LoomGradleExtension; import net.fabricmc.loom.LoomGradlePlugin;
import net.fabricmc.loom.configuration.ide.RunConfig; import net.fabricmc.loom.configuration.ide.RunConfig;
import net.fabricmc.loom.configuration.ide.RunConfigSettings; import net.fabricmc.loom.configuration.ide.RunConfigSettings;
@ -48,7 +46,6 @@ public class GenVsCodeProjectTask extends AbstractLoomTask {
@TaskAction @TaskAction
public void genRuns() { public void genRuns() {
Project project = getProject(); Project project = getProject();
LoomGradleExtension extension = getExtension();
File projectDir = project.file(".vscode"); File projectDir = project.file(".vscode");
if (!projectDir.exists()) { if (!projectDir.exists()) {
@ -72,8 +69,7 @@ public class GenVsCodeProjectTask extends AbstractLoomTask {
settings.makeRunDir(); settings.makeRunDir();
} }
Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = LoomGradlePlugin.GSON.toJson(launch);
String json = gson.toJson(launch);
try { try {
FileUtils.writeStringToFile(launchJson, json, StandardCharsets.UTF_8); FileUtils.writeStringToFile(launchJson, json, StandardCharsets.UTF_8);

View File

@ -34,7 +34,7 @@ import net.fabricmc.loom.configuration.RemappedConfigurationEntry;
public class Constants { public class Constants {
public static final String LIBRARIES_BASE = "https://libraries.minecraft.net/"; public static final String LIBRARIES_BASE = "https://libraries.minecraft.net/";
public static final String RESOURCES_BASE = "http://resources.download.minecraft.net/"; public static final String RESOURCES_BASE = "https://resources.download.minecraft.net/";
public static final String VERSION_MANIFESTS = "https://launchermeta.mojang.com/mc/game/version_manifest_v2.json"; public static final String VERSION_MANIFESTS = "https://launchermeta.mojang.com/mc/game/version_manifest_v2.json";
public static final String SYSTEM_ARCH = System.getProperty("os.arch").equals("64") ? "64" : "32"; public static final String SYSTEM_ARCH = System.getProperty("os.arch").equals("64") ? "64" : "32";

View File

@ -36,8 +36,8 @@ public final class GroovyXmlUtil {
public static Node getOrCreateNode(Node parent, String name) { public static Node getOrCreateNode(Node parent, String name) {
for (Object object : parent.children()) { for (Object object : parent.children()) {
if (object instanceof Node && isSameName(((Node) object).name(), name)) { if (object instanceof Node node && isSameName(node.name(), name)) {
return (Node) object; return node;
} }
} }
@ -46,8 +46,8 @@ public final class GroovyXmlUtil {
public static Optional<Node> getNode(Node parent, String name) { public static Optional<Node> getNode(Node parent, String name) {
for (Object object : parent.children()) { for (Object object : parent.children()) {
if (object instanceof Node && isSameName(((Node) object).name(), name)) { if (object instanceof Node node && isSameName(node.name(), name)) {
return Optional.of((Node) object); return Optional.of(node);
} }
} }
@ -59,13 +59,13 @@ public final class GroovyXmlUtil {
return nodeName.equals(givenName); return nodeName.equals(givenName);
} }
if (nodeName instanceof QName) { if (nodeName instanceof QName qName) {
return ((QName) nodeName).matches(givenName); return qName.matches(givenName);
} }
// New groovy 3 (gradle 7) class // New groovy 3 (gradle 7) class
if (nodeName instanceof groovy.namespace.QName) { if (nodeName instanceof groovy.namespace.QName qName) {
return ((groovy.namespace.QName) nodeName).matches(givenName); return qName.matches(givenName);
} }
throw new UnsupportedOperationException("Cannot determine if " + nodeName.getClass() + " is the same as a String"); throw new UnsupportedOperationException("Cannot determine if " + nodeName.getClass() + " is the same as a String");

View File

@ -234,7 +234,7 @@ public class SourceRemapper {
} }
} else { } else {
for (RemappedConfigurationEntry entry : Constants.MOD_COMPILE_ENTRIES) { for (RemappedConfigurationEntry entry : Constants.MOD_COMPILE_ENTRIES) {
for (File inputFile : project.getConfigurations().getByName(entry.getSourceConfiguration()).getFiles()) { for (File inputFile : project.getConfigurations().getByName(entry.sourceConfiguration()).getFiles()) {
m.getClassPath().add(inputFile.toPath()); m.getClassPath().add(inputFile.toPath());
} }
} }

View File

@ -61,8 +61,8 @@ public final class StaticPathWatcher {
for (WatchEvent<?> event : key.pollEvents()) { for (WatchEvent<?> event : key.pollEvents()) {
Object ctx = event.context(); Object ctx = event.context();
if (ctx instanceof Path) { if (ctx instanceof Path path) {
changeCache.put(((Path) ctx).toAbsolutePath(), true); changeCache.put(path.toAbsolutePath(), true);
} }
} }
} }