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
This commit is contained in:
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.
* 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.
* Loom targets a wide range of Gradle versions. _Tested with 4.9 up to 6.7_
* Supports the latest version of Java all the way down to Java 8
* Loom targets the latest version of Gradle 7 or newer
* Supports Java 16 upwards
## Use Loom to develop mods

View file

@ -46,6 +46,7 @@ dependencies {
implementation ('commons-io:commons-io:2.8.0')
implementation ('org.zeroturnaround:zt-zip:1.14')
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 ('org.ow2.asm:asm:9.1')
implementation ('org.ow2.asm:asm-analysis:9.1')
@ -70,21 +71,21 @@ dependencies {
implementation ('org.cadixdev:lorenz-io-proguard:0.5.6')
// decompilers
implementation ('net.fabricmc:fabric-fernflower:1.3.0')
implementation ('org.benf:cfr:0.150')
implementation ('net.fabricmc:fabric-fernflower:1.4.0')
implementation ('org.benf:cfr:0.151')
// source code remapping
implementation ('org.cadixdev:mercury:0.1.0-rc1')
// Kapt integration
compileOnly('org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.32')
compileOnly('org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.0')
// Testing
testImplementation(gradleTestKit())
testImplementation('org.spockframework:spock-core:2.0-M5-groovy-3.0') {
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'
}
@ -115,11 +116,11 @@ license {
checkstyle {
configFile = file('checkstyle.xml')
toolVersion = '8.41.1'
toolVersion = '8.42'
}
codenarc {
toolVersion = "2.0.0"
toolVersion = "2.1.0"
configFile = file("codenarc.groovy")
}

View file

@ -24,6 +24,8 @@
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.gson.Gson;
import com.google.gson.GsonBuilder;
@ -41,6 +43,7 @@ import net.fabricmc.loom.task.LoomTasks;
public class LoomGradlePlugin implements Plugin<Project> {
public static boolean refreshDeps;
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
public void apply(Project project) {

View file

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

View file

@ -69,7 +69,7 @@ public class ModCompileRemapper {
for (RemappedConfigurationEntry entry : Constants.MOD_COMPILE_ENTRIES) {
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()));
List<ModDependencyInfo> modDependencies = new ArrayList<>();
@ -149,8 +149,8 @@ public class ModCompileRemapper {
Dependency dep = dependencies.module(artifact.getModuleVersion().toString()
+ (artifact.getClassifier() == null ? "" : ':' + artifact.getClassifier())); // the owning module of the artifact
if (dep instanceof ModuleDependency) {
((ModuleDependency) dep).setTransitive(false);
if (dep instanceof ModuleDependency moduleDependency) {
moduleDependency.setTransitive(false);
}
dependencies.add(regularCompile.getName(), dep);

View file

@ -71,7 +71,7 @@ public abstract class AnnotationProcessorInvoker<T extends Task> {
private void passMixinArguments(T task) {
try {
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.OUT_MAP_FILE_NAMED_INTERMEDIARY, extension.getNextMixinMappings().getCanonicalPath());
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.stream.Collectors;
public class MergedNestedJarProvider implements NestedJarProvider {
private final NestedJarProvider[] parents;
public MergedNestedJarProvider(NestedJarProvider... parents) {
this.parents = parents;
}
public record MergedNestedJarProvider(NestedJarProvider... parents) implements NestedJarProvider {
@Override
public Collection<File> provide() {
return Arrays.stream(parents)

View file

@ -80,13 +80,12 @@ public final class NestedDependencyProvider implements NestedJarProvider {
DependencySet dependencies = configuration.getDependencies();
for (Dependency dependency : dependencies) {
if (dependency instanceof ProjectDependency) {
ProjectDependency projectDependency = (ProjectDependency) dependency;
if (dependency instanceof ProjectDependency projectDependency) {
Project dependencyProject = projectDependency.getDependencyProject();
for (Task task : dependencyProject.getTasksByName("remapJar", false)) {
if (task instanceof RemapJarTask) {
remapTasks.add((RemapJarTask) task);
if (task instanceof RemapJarTask remapJarTask) {
remapTasks.add(remapJarTask);
}
}
}
@ -99,8 +98,7 @@ public final class NestedDependencyProvider implements NestedJarProvider {
List<DependencyInfo<ProjectDependency>> fileList = new ArrayList<>();
for (Dependency dependency : configuration.getDependencies()) {
if (dependency instanceof ProjectDependency) {
ProjectDependency projectDependency = (ProjectDependency) dependency;
if (dependency instanceof ProjectDependency projectDependency) {
Project dependencyProject = projectDependency.getDependencyProject();
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);
for (Task task : remapJarTasks.isEmpty() ? jarTasks : remapJarTasks) {
if (task instanceof RemapJarTask) {
File file = ((RemapJarTask) task).getArchivePath();
if (task instanceof RemapJarTask remapJarTask) {
File file = remapJarTask.getArchiveFile().get().getAsFile();
fileList.add(new DependencyInfo<>(projectDependency, new ProjectDependencyMetaExtractor(), file));
} else if (task instanceof AbstractArchiveTask) {
File file = ((AbstractArchiveTask) task).getArchivePath();
} else if (task instanceof AbstractArchiveTask abstractArchiveTask) {
File file = abstractArchiveTask.getArchiveFile().get().getAsFile();
fileList.add(new DependencyInfo<>(projectDependency, new ProjectDependencyMetaExtractor(), file));
}
}
@ -208,17 +206,7 @@ public final class NestedDependencyProvider implements NestedJarProvider {
return LoomGradlePlugin.GSON.toJson(jsonObject);
}
private static class DependencyInfo<D> {
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;
}
private record DependencyInfo<D>(D dependency, DependencyMetaExtractor<D> metaExtractor, File file) {
public void validateInputs() {
if (!file.exists()) {
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);
for (RemappedConfigurationEntry entry : Constants.MOD_COMPILE_ENTRIES) {
data.createLazyConfiguration(entry.getSourceConfiguration())
data.createLazyConfiguration(entry.sourceConfiguration())
.configure(configuration -> configuration.setTransitive(true));
// Don't get transitive deps of already remapped mods
@ -77,7 +77,7 @@ public final class CompileConfiguration {
extendsFrom(entry.getTargetConfiguration(configurations), entry.getRemappedConfiguration(), project);
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);
}
}

View file

@ -100,8 +100,8 @@ public abstract class DependencyProvider {
private String resolvedVersion = null;
public static DependencyInfo create(Project project, Dependency dependency, Configuration sourceConfiguration) {
if (dependency instanceof SelfResolvingDependency) {
return new FileDependencyInfo(project, (SelfResolvingDependency) dependency, sourceConfiguration);
if (dependency instanceof SelfResolvingDependency selfResolvingDependency) {
return new FileDependencyInfo(project, selfResolvingDependency, sourceConfiguration);
} else {
return new DependencyInfo(project, dependency, sourceConfiguration);
}
@ -138,8 +138,8 @@ public abstract class DependencyProvider {
}
public Set<File> resolve() {
if (dependency instanceof SelfResolvingDependency) {
return ((SelfResolvingDependency) dependency).resolve();
if (dependency instanceof SelfResolvingDependency selfResolvingDependency) {
return selfResolvingDependency.resolve();
}
return sourceConfiguration.files(dependency);
@ -189,14 +189,11 @@ public abstract class DependencyProvider {
Set<File> files = dependency.resolve();
this.resolvedFiles = files;
switch (files.size()) {
case 0: //Don't think Gradle would ever let you do this
throw new IllegalStateException("Empty dependency?");
case 1: //Single file dependency
classifierToFile.put("", Iterables.getOnlyElement(files));
break;
default: //File collection, try work out the classifiers
case 0 -> //Don't think Gradle would ever let you do this
throw new IllegalStateException("Empty dependency?");
case 1 -> //Single file dependency
classifierToFile.put("", Iterables.getOnlyElement(files));
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());
//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);
@ -223,6 +220,7 @@ public abstract class DependencyProvider {
}
}
}
}
if (dependency.getGroup() != null && dependency.getVersion() != null) {
group = dependency.getGroup();

View file

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

View file

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

View file

@ -36,7 +36,6 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.io.IOUtils;
import org.gradle.api.Project;
import org.gradle.api.tasks.SourceSet;
import org.gradle.plugins.ide.eclipse.model.EclipseModel;
@ -222,7 +221,7 @@ public class RunConfig {
String dummyConfig;
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);

View file

@ -42,7 +42,6 @@ import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import com.google.gson.JsonObject;
import org.apache.commons.io.IOUtils;
import org.gradle.api.Project;
import org.objectweb.asm.commons.Remapper;
import org.zeroturnaround.zip.ZipUtil;
@ -156,7 +155,7 @@ public class ModProcessor {
final Map<ModDependencyInfo, byte[]> accessWidenerMap = new HashMap<>();
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))) {
project.getLogger().debug("Adding " + inputFile + " onto the remap classpath");
@ -229,7 +228,7 @@ public class ModProcessor {
}
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 org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.gradle.api.artifacts.Configuration;
import org.jetbrains.annotations.Nullable;
@ -80,7 +79,7 @@ public class ModDependencyInfo {
}
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() {
@ -96,7 +95,7 @@ public class ModDependencyInfo {
}
private String getGroup() {
return getMappingsPrefix(remapData.mappingsSuffix) + "." + group;
return getMappingsPrefix(remapData.mappingsSuffix()) + "." + group;
}
public static String getMappingsPrefix(String mappings) {
@ -121,7 +120,7 @@ public class ModDependencyInfo {
String pomTemplate;
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

View file

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

View file

@ -65,7 +65,7 @@ public class LaunchProvider extends DependencyProvider {
.property("client", "org.lwjgl.librarypath", getExtension().getNativesDirectory().getAbsolutePath())
.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", new File(getExtension().getUserCache(), "assets").getAbsolutePath());
@ -112,7 +112,7 @@ public class LaunchProvider extends DependencyProvider {
private void writeRemapClassPath() {
List<String> inputConfigurations = new ArrayList<>();
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<>();
@ -127,7 +127,7 @@ public class LaunchProvider extends DependencyProvider {
.collect(Collectors.joining(File.pathSeparator));
try {
Files.write(getRemapClasspathFile().toPath(), str.getBytes(StandardCharsets.UTF_8));
Files.writeString(getRemapClasspathFile().toPath(), str);
} catch (IOException 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 com.google.common.io.Files;
import com.google.gson.GsonBuilder;
import org.gradle.api.GradleException;
import org.gradle.api.Project;
import org.gradle.api.logging.Logger;
@ -75,7 +74,7 @@ public class MinecraftProvider extends DependencyProvider {
downloadMcJson(offline);
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
@ -140,7 +139,7 @@ public class MinecraftProvider extends DependencyProvider {
}
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();
@ -153,7 +152,7 @@ public class MinecraftProvider extends DependencyProvider {
}
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()) {
@ -197,8 +196,8 @@ public class MinecraftProvider extends DependencyProvider {
return false;
}
ManifestVersion manifest = new GsonBuilder().create().fromJson(Files.asCharSource(versionManifestJson, StandardCharsets.UTF_8).read(), ManifestVersion.class);
Optional<ManifestVersion.Versions> version = manifest.versions.stream().filter(versions -> versions.id.equalsIgnoreCase(minecraftVersion)).findFirst();
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();
// fail if the expected mc version was not found, will download the file again.
return version.isPresent();
@ -209,11 +208,11 @@ public class MinecraftProvider extends DependencyProvider {
return;
}
MinecraftVersionMeta.Download client = versionInfo.getDownload("client");
MinecraftVersionMeta.Download server = versionInfo.getDownload("server");
MinecraftVersionMeta.Download client = versionInfo.download("client");
MinecraftVersionMeta.Download server = versionInfo.download("server");
HashedDownloadUtil.downloadIfInvalid(new URL(client.getUrl()), minecraftClientJar, client.getSha1(), logger, false);
HashedDownloadUtil.downloadIfInvalid(new URL(server.getUrl()), minecraftServerJar, server.getSha1(), logger, false);
HashedDownloadUtil.downloadIfInvalid(new URL(client.url()), minecraftClientJar, client.sha1(), logger, false);
HashedDownloadUtil.downloadIfInvalid(new URL(server.url()), minecraftServerJar, server.sha1(), logger, false);
}
private void mergeJars(Logger logger) throws IOException {

View file

@ -28,7 +28,6 @@ import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
@ -259,7 +258,7 @@ public class MappingsProvider extends DependencyProvider {
}
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) {
throw new UnsupportedOperationException("Unsupported unpick version");
@ -409,13 +408,6 @@ public class MappingsProvider extends DependencyProvider {
return hasUnpickDefinitions;
}
public static class UnpickMetadata {
public final String unpickGroup;
public final String unpickVersion;
public UnpickMetadata(String unpickGroup, String unpickVersion) {
this.unpickGroup = unpickGroup;
this.unpickVersion = unpickVersion;
}
public record UnpickMetadata(String unpickGroup, String unpickVersion) {
}
}

View file

@ -123,15 +123,15 @@ public class MojangMappingsDependency implements SelfResolvingDependency {
private MappingSet getMappingsSet(Path clientMappings, Path serverMappings) throws IOException {
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());
}
MinecraftVersionMeta.Download clientMappingsDownload = versionInfo.getDownload(MANIFEST_CLIENT_MAPPINGS);
MinecraftVersionMeta.Download serverMappingsDownload = versionInfo.getDownload(MANIFEST_CLIENT_MAPPINGS);
MinecraftVersionMeta.Download clientMappingsDownload = versionInfo.download(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(serverMappingsDownload.getUrl()), serverMappings.toFile(), clientMappingsDownload.getSha1(), project.getLogger(), false);
HashedDownloadUtil.downloadIfInvalid(new URL(clientMappingsDownload.url()), clientMappings.toFile(), clientMappingsDownload.sha1(), project.getLogger(), false);
HashedDownloadUtil.downloadIfInvalid(new URL(serverMappingsDownload.url()), serverMappings.toFile(), clientMappingsDownload.sha1(), project.getLogger(), false);
MappingSet mappings = MappingSet.create();
@ -208,8 +208,8 @@ public class MojangMappingsDependency implements SelfResolvingDependency {
@Override
public boolean contentEquals(Dependency dependency) {
if (dependency instanceof MojangMappingsDependency) {
return ((MojangMappingsDependency) dependency).extension.getMinecraftProvider().getMinecraftVersion().equals(getVersion());
if (dependency instanceof MojangMappingsDependency mojangMappingsDependency) {
return mojangMappingsDependency.extension.getMinecraftProvider().getMinecraftVersion().equals(getVersion());
}
return false;

View file

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

View file

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

View file

@ -89,11 +89,11 @@ public class MinecraftNativesProvider {
nativesDir.mkdirs();
for (MinecraftVersionMeta.Classifier library : getNatives()) {
File libJarFile = library.getRelativeFile(jarStore);
for (MinecraftVersionMeta.Download library : getNatives()) {
File libJarFile = library.relativeFile(jarStore);
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()) {
@ -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
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() {
List<MinecraftVersionMeta.Classifier> natives = getNatives();
List<MinecraftVersionMeta.Download> natives = getNatives();
if (natives.isEmpty()) {
throw new IllegalStateException("No natives found for the current system");
}
for (MinecraftVersionMeta.Classifier library : natives) {
File libJarFile = library.getRelativeFile(jarStore);
for (MinecraftVersionMeta.Download library : natives) {
File libJarFile = library.relativeFile(jarStore);
File libSha1File = new File(nativesDir, libJarFile.getName() + ".sha1");
if (!libSha1File.exists()) {
@ -126,7 +126,7 @@ public class MinecraftNativesProvider {
try {
String sha1 = FileUtils.readFileToString(libSha1File, StandardCharsets.UTF_8);
if (!sha1.equalsIgnoreCase(library.getSha1())) {
if (!sha1.equalsIgnoreCase(library.sha1())) {
return true;
}
} catch (IOException e) {
@ -139,10 +139,10 @@ public class MinecraftNativesProvider {
return false;
}
private List<MinecraftVersionMeta.Classifier> getNatives() {
return extension.getMinecraftProvider().getVersionInfo().getLibraries().stream()
private List<MinecraftVersionMeta.Download> getNatives() {
return extension.getMinecraftProvider().getVersionInfo().libraries().stream()
.filter((MinecraftVersionMeta.Library::hasNativesForOS))
.map(MinecraftVersionMeta.Library::getClassifierForOS)
.map(MinecraftVersionMeta.Library::classifierForOS)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}

View file

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

View file

@ -30,23 +30,12 @@ import java.util.Map;
import java.util.Set;
@SuppressWarnings("unused")
public class AssetIndex {
private final Map<String, AssetObject> objects;
private boolean virtual;
public record AssetIndex(Map<String, AssetObject> objects, boolean virtual) {
public AssetIndex() {
this.objects = new LinkedHashMap<>();
}
public Map<String, AssetObject> getFileMap() {
return this.objects;
this(new LinkedHashMap<>(), false);
}
public Set<AssetObject> getUniqueObjects() {
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;
@SuppressWarnings("unused")
public class AssetObject {
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;
}
public record AssetObject(String hash, long size) {
}

View file

@ -53,7 +53,7 @@ public class MinecraftAssetsProvider {
boolean offline = project.getGradle().getStartParameter().isOffline();
MinecraftVersionMeta versionInfo = minecraftProvider.getVersionInfo();
MinecraftVersionMeta.AssetIndex assetIndex = versionInfo.getAssetIndex();
MinecraftVersionMeta.AssetIndex assetIndex = versionInfo.assetIndex();
// get existing cache files
File assets = new File(extension.getUserCache(), "assets");
@ -62,7 +62,7 @@ public class MinecraftAssetsProvider {
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");
@ -75,7 +75,7 @@ public class MinecraftAssetsProvider {
throw new GradleException("Asset index not found at " + assetsInfo.getAbsolutePath());
}
} 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<>();
@ -84,16 +84,16 @@ public class MinecraftAssetsProvider {
AssetIndex index;
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();
Map<String, AssetObject> parent = index.getFileMap();
Map<String, AssetObject> parent = index.objects();
for (Map.Entry<String, AssetObject> entry : parent.entrySet()) {
AssetObject object = entry.getValue();
String sha1 = object.getHash();
String sha1 = object.hash();
String filename = "objects" + File.separator + sha1.substring(0, 2) + File.separator + sha1;
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 {
Files.walkFileTree(input, new SimpleFileVisitor<Path>() {
Files.walkFileTree(input, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
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.collect.ImmutableMap;
import com.google.common.io.ByteStreams;
import org.benf.cfr.reader.api.CfrDriver;
import org.benf.cfr.reader.api.ClassFileSource;
import org.benf.cfr.reader.api.OutputSinkFactory;
@ -134,36 +133,29 @@ public class FabricCFRDecompiler implements LoomDecompiler {
}
try (InputStream inputStream = inputZip.getInputStream(zipEntry)) {
return Pair.make(ByteStreams.toByteArray(inputStream), path);
return Pair.make(inputStream.readAllBytes(), path);
}
}
})
.withOutputSink(new OutputSinkFactory() {
@Override
public List<SinkClass> getSupportedSinks(SinkType sinkType, Collection<SinkClass> available) {
switch (sinkType) {
case PROGRESS:
return Collections.singletonList(SinkClass.STRING);
case JAVA:
return Collections.singletonList(SinkClass.DECOMPILED);
default:
return Collections.emptyList();
}
return switch (sinkType) {
case PROGRESS -> Collections.singletonList(SinkClass.STRING);
case JAVA -> Collections.singletonList(SinkClass.DECOMPILED);
default -> Collections.emptyList();
};
}
@SuppressWarnings("unchecked")
@Override
public <T> Sink<T> getSink(SinkType sinkType, SinkClass sinkClass) {
switch (sinkType) {
case PROGRESS:
return (p) -> project.getLogger().debug((String) p);
case JAVA:
return (Sink<T>) decompiledSink(jos, addedDirectories);
case EXCEPTION:
return (e) -> project.getLogger().error((String) e);
}
return null;
return switch (sinkType) {
case PROGRESS -> (p) -> project.getLogger().debug((String) p);
case JAVA -> (Sink<T>) decompiledSink(jos, addedDirectories);
case EXCEPTION -> (e) -> project.getLogger().error((String) e);
default -> null;
};
}
})
.build();
@ -173,7 +165,7 @@ public class FabricCFRDecompiler implements LoomDecompiler {
.filter(input -> input.endsWith(".class"))
.collect(Collectors.toList());
ExecutorService executorService = Executors.newFixedThreadPool(metaData.numberOfThreads);
ExecutorService executorService = Executors.newFixedThreadPool(metaData.numberOfThreads());
List<Future<?>> futures = new LinkedList<>();
for (String clazz : classes) {

View file

@ -65,12 +65,12 @@ public abstract class AbstractFernFlowerDecompiler implements LoomDecompiler {
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.BYTECODE_SOURCE_MAPPING, "1");
put(IFernflowerPreferences.REMOVE_SYNTHETIC, "1");
put(IFernflowerPreferences.LOG_LEVEL, "trace");
put(IFernflowerPreferences.THREADS, metaData.numberOfThreads);
put(IFernflowerPreferences.THREADS, metaData.numberOfThreads());
}};
List<String> args = new ArrayList<>();
@ -79,10 +79,10 @@ public abstract class AbstractFernFlowerDecompiler implements LoomDecompiler {
args.add(absolutePathOf(compiledJar));
args.add("-o=" + absolutePathOf(sourcesDestination));
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?
for (Path library : metaData.libraries) {
for (Path library : metaData.libraries()) {
args.add("-e=" + absolutePathOf(library));
}

View file

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

View file

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

View file

@ -234,7 +234,7 @@ public class SourceRemapper {
}
} else {
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());
}
}

View file

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