Files
Iris/core/build.gradle
T
piexel 8748d85e37 Reuse VolmLib's hunk, interpolation and face types and drop the dead util wrappers
Iris carried copies of VolmLib's storage hunks, interpolation statics and HunkFace, plus wrappers nothing used. The storage hunks and IrisInterpolation now extend VolmLib's, Hunk uses VolmLib's HunkFace, and the Iris rangeScale stays so interpolation output does not change. The newly shipped VolmLib classes leave the Bukkit jar's left-out list.

Upstream: 355d7f413 355161408 114cc68a0
2026-11-10 01:16:52 +01:00

481 lines
20 KiB
Groovy

import io.github.slimjar.resolver.data.Mirror
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.jvm.tasks.Jar
import org.gradle.jvm.toolchain.JavaLanguageVersion
import java.net.URI
import java.nio.charset.StandardCharsets
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2021 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
plugins {
id 'java'
id 'java-library'
alias(libs.plugins.shadow)
alias(libs.plugins.slimjar)
}
def lib = 'art.arcane.iris.util'
String volmLibCoordinate = providers.gradleProperty('volmLibCoordinate')
.orElse('com.github.VolmitSoftware:VolmLib:e6574cf814b3dd670385a4d632a63fde2038e186')
.get()
/**
* Dependencies.
*
* Provided or classpath dependencies are not shaded and are available on the runtime classpath
*
* Shaded dependencies are not available at runtime, nor are they available on mvn central so they
* need to be shaded into the jar (increasing binary size)
*
* Dynamically loaded dependencies are defined in the plugin.yml (updating these must be updated in the
* plugin.yml also, otherwise they wont be available). These do not increase binary size). Only declare
* these dependencies if they are available on mvn central.
*/
dependencies {
api(project(':spi'))
// IrisApi, from the sibling checkout (gradle/irisapi-resolution.settings.gradle). Shaded without
// relocation: pack modules compile against com.volmit and the pack loader exposes that package,
// except the host side (com.volmit.host), which loads and runs them.
implementation('com.volmit:iris-api')
implementation('com.volmit:iris-host')
// The built-in modules (IrisModule, a build of its own against the Iris API). Core and the adapters still name their
// classes; the ones in the built-ins jar are left out of the plugin and load from the jar it bundles.
api('art.arcane:iris-module')
// Provided or Classpath
compileOnly(libs.lombok)
annotationProcessor(libs.lombok)
compileOnly(libs.paper.api)
compileOnly(libs.log4j.api)
compileOnly(libs.log4j.core)
compileOnly(libs.guava)
// Third Party Integrations
compileOnly(libs.nexo)
compileOnly(libs.itemsadder)
compileOnly(libs.score)
compileOnly(libs.mmoitems)
compileOnly(libs.mythiclib)
compileOnly(libs.eco)
compileOnly(libs.mythic)
compileOnly(libs.mythicCrucible)
compileOnly(libs.kgenerators) {
transitive = false
}
compileOnly(libs.multiverseCore)
compileOnly(libs.craftengine.core)
compileOnly(libs.craftengine.bukkit)
// Shaded
implementation('de.crazydev22.slimjar.helper:spigot:2.1.9')
implementation(volmLibCoordinate) {
transitive = false
}
// Dynamically Loaded
slim(libs.gson)
slim(libs.lru)
slim(libs.caffeine)
slim(libs.paralithic)
slim(libs.paperlib)
slim(libs.adventure.api)
slim(libs.adventure.minimessage)
slim(libs.adventure.serializer.legacy)
slim(libs.adventure.serializer.plain)
slim(libs.bstats)
slim(libs.commons.io)
slim(libs.commons.lang3)
slim(libs.oshi)
slim(libs.lz4)
slim(libs.fastutil)
slim(libs.zip) {
exclude(group: 'org.slf4j', module: 'slf4j-api')
}
slim(libs.asm)
slim(libs.byteBuddy.core)
slim(libs.byteBuddy.agent)
slim(libs.dom4j)
slim(libs.jaxen)
testImplementation('com.volmit:iris-api')
testImplementation('com.volmit:iris-host')
testImplementation('junit:junit:4.13.2')
testImplementation('org.mockito:mockito-core:5.23.0')
testImplementation(libs.paper.api)
testRuntimeOnly(libs.paper.api)
testImplementation(libs.multiverseCore)
}
tasks.named('test').configure {
maxHeapSize = '1g'
systemProperty('iris.packBenchmarkingSource', file('src/main/java/art/arcane/iris/core/tools/IrisPackBenchmarking.java').absolutePath)
systemProperty('iris.irisToolbeltSource', file('src/main/java/art/arcane/iris/core/tools/IrisToolbelt.java').absolutePath)
systemProperty('iris.irisCreatorSource', file('src/main/java/art/arcane/iris/core/tools/IrisCreator.java').absolutePath)
systemProperty('iris.bukkitChunkGeneratorSource', file('src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java').absolutePath)
systemProperty('iris.defaultModuleSources', rootProject.file('module/src/main/java').absolutePath)
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
slimJar {
mirrors = [
new Mirror(
URI.create('https://maven-central.storage-download.googleapis.com/maven2').toURL(),
URI.create('https://repo.maven.apache.org/maven2/').toURL()
)
]
relocate('com.dfsek.paralithic', "${lib}.paralithic")
relocate('com.google.gson', "${lib}.gson")
relocate('com.googlecode.concurrentlinkedhashmap', "${lib}.lru")
relocate('io.papermc.lib', "${lib}.paper")
relocate('net.kyori', "${lib}.kyori")
relocate('org.bstats', "${lib}.metrics")
relocate('org.apache.maven', "${lib}.maven")
relocate('org.codehaus.plexus', "${lib}.plexus")
relocate('org.eclipse.sisu', "${lib}.sisu")
relocate('org.eclipse.aether', "${lib}.aether")
relocate('com.google.inject', "${lib}.guice")
relocate('org.dom4j', "${lib}.dom4j")
relocate('org.jaxen', "${lib}.jaxen")
relocate('com.github.benmanes.caffeine', "${lib}.caffeine")
}
def embeddedAgentJar = project(':core:agent').tasks.named('jar', Jar)
def templateSource = file('src/main/templates')
def templateDest = layout.buildDirectory.dir('generated/sources/templates')
def generateTemplates = tasks.register('generateTemplates', Copy) {
inputs.properties([
environment: providers.provider {
if (project.hasProperty('release')) {
return 'production'
}
if (project.hasProperty('argghh')) {
return 'Argghh!'
}
return 'development'
},
commit: providers.provider {
String commitId = null
Exception failure = null
try {
Process process = new ProcessBuilder('git', '-C', rootProject.projectDir.absolutePath, 'rev-parse', 'HEAD')
.redirectErrorStream(true)
.start()
String output = new String(process.inputStream.readAllBytes(), StandardCharsets.UTF_8).trim()
int exitCode = process.waitFor()
if (exitCode == 0) {
commitId = output
} else {
failure = new GradleException("git rev-parse exited with code ${exitCode}: ${output}")
}
} catch (Exception ex) {
failure = ex
}
if (commitId != null && commitId.length() == 40) {
return commitId
}
logger.error('Git commit hash not found', failure)
return 'unknown'
},
minecraftVersion: providers.gradleProperty('minecraftVersion'),
])
from(templateSource)
into(templateDest)
rename { String fileName -> "art/arcane/iris/${fileName}" }
expand(inputs.properties)
}
tasks.named('compileJava', JavaCompile).configure {
/**
* We need parameter meta for the decree command system
*/
options.compilerArgs.add('-parameters')
options.compilerArgs.addAll(['--add-modules', 'jdk.incubator.vector'])
options.encoding = 'UTF-8'
options.debugOptions.debugLevel = 'none'
// lombok.config decides how equals/hashCode/toString are generated (fields, never getters), so editing it
// changes this module's bytecode. Gradle does not know that on its own and would serve a stale up-to-date
// build until something else in the module changed.
inputs.file(rootProject.file('lombok.config'))
.withPropertyName('lombokConfig')
.withPathSensitivity(PathSensitivity.NONE)
}
tasks.named('test', Test).configure {
jvmArgs('--add-modules', 'jdk.incubator.vector')
classpath = files('src/main/resources') + classpath
}
configurations.matching { it.name.startsWith('slim') }.all { }
List<String> requestedTasks = gradle.startParameter.taskNames
boolean runningOnlyTestTasks = !requestedTasks.isEmpty()
&& requestedTasks.every { String taskName -> taskName.toLowerCase().contains('test') }
if (runningOnlyTestTasks) {
TaskProvider<Task> processResourcesTask = tasks.named('processResources')
tasks.named('classes').configure { Task classesTask ->
Set<Object> dependencies = new LinkedHashSet<Object>(classesTask.getDependsOn())
dependencies.removeIf { Object dependency ->
if (dependency instanceof TaskProvider) {
return ((TaskProvider<?>) dependency).name == processResourcesTask.name
}
if (dependency instanceof Task) {
return ((Task) dependency).name == processResourcesTask.name
}
String dependencyName = String.valueOf(dependency)
return dependencyName == 'processResources' || dependencyName.endsWith(':processResources')
}
classesTask.setDependsOn(dependencies)
}
processResourcesTask.configure { Task task ->
task.enabled = false
}
}
// Iris's own packages and classes the Bukkit jar leaves out: nothing shipped in the jar reaches them (the list's
// package-granularity reasoning is in the header of volmlib-left-out-of-bukkit-jar.txt). verifyBukkitArtifact re-derives
// the reference graph over the shipped jar and fails on any dangling reference, so an exclude that stops being dead is a
// build failure rather than a runtime crash.
List<String> irisPackagesLeftOut = [
'art/arcane/iris/core/report/**'
]
List<String> irisClassesLeftOut = [
'art/arcane/iris/core/pack/IrisPack',
'art/arcane/iris/core/pack/IrisPackRepository',
'art/arcane/iris/core/jobs/DownloadJob',
'art/arcane/iris/core/jobs/JobCollection',
'art/arcane/iris/core/jobs/ParallelQueueJob',
'art/arcane/iris/core/jobs/QueueJob',
'art/arcane/iris/engine/object/placement/IPostBlockAccess',
'art/arcane/iris/engine/object/entity/IrisPotionEffect',
'art/arcane/iris/engine/platform/DummyChunkGenerator',
'art/arcane/iris/util/common/parallel/GridLock',
'art/arcane/iris/util/common/reflect/W',
'art/arcane/iris/util/slimjar/BuildConstants',
'art/arcane/iris/util/slimjar/relocation/meta/AttributeMetaMediator',
'art/arcane/iris/util/slimjar/relocation/meta/AttributeMetaMediatorFactory'
]
// The VolmLib classes the jar leaves out are listed in a file the built-in modules jar check reads too (IrisModule), so a
// module cannot use a VolmLib class that is stripped from here. Format: see the file's header.
File volmLibLeftOutFile = file('volmlib-left-out-of-bukkit-jar.txt')
List<String> volmLibLeftOutEntries = volmLibLeftOutFile.readLines()
.collect { String line -> line.contains('#') ? line.substring(0, line.indexOf('#')).trim() : line.trim() }
.findAll { String line -> !line.isEmpty() }
.collectMany { String entry ->
entry.endsWith('.class') || entry.contains('*') ? [entry] : [entry + '.class', entry + '$*.class']
}
List<String> irisClassesLeftOutEntries = irisClassesLeftOut.collectMany { String classPath ->
[classPath + '.class', classPath + '$*.class']
}
// Annotation-only artifacts pulled in transitively by Gson and Caffeine. Their types appear solely
// in annotation attributes, which the JVM skips silently when the type is absent, so nothing loads
// or links against them at runtime.
List<String> annotationOnlyArtifacts = [
'com/google/errorprone/**',
'org/jspecify/**'
]
// Publisher metadata for the shaded dependencies. Nothing reads these at runtime.
List<String> dependencyBuildMetadata = [
'META-INF/maven/**',
'META-INF/proguard/**',
'META-INF/versions/*/OSGI-INF/**'
]
// The built-in modules as a pack module jar, iris-builtins.jar, which IrisModule builds from its classes and checks as a pack
// load would. Iris bundles it into the plugin (IrisModuleHost loads it with every pack) after checking it once more against
// what its own Bukkit jar leaves out of VolmLib, which only Iris knows.
String builtinModulesJarName = 'iris-builtins.jar'
// The packages pack modules may use besides the IrisApi; IrisModuleHost.EXPOSED_PACKAGES lists the same.
List<String> builtinExposedPackages = ['art.arcane.iris.builtin', 'art.arcane.volmlib', 'com.google.gson']
Provider<RegularFile> bundledBuiltinModulesJar = layout.buildDirectory.file("builtin-modules/${builtinModulesJarName}")
configurations {
builtinModules {
canBeConsumed = false
transitive = false
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage, Usage.JAVA_RUNTIME))
}
}
// What the check sees besides the jar: the IrisApi (its host side included, as in the plugin, where the check finds it
// hidden), the libraries Iris shares with pack modules, and the module classes that are not in the jar.
builtinModulesCheckClasspath {
canBeConsumed = false
transitive = false
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage, Usage.JAVA_RUNTIME))
}
}
}
dependencies {
builtinModules('art.arcane:iris-module') {
capabilities {
requireCapability('art.arcane:iris-builtins')
}
}
builtinModulesCheckClasspath('com.volmit:iris-api')
builtinModulesCheckClasspath('com.volmit:iris-host')
builtinModulesCheckClasspath('art.arcane:iris-module')
builtinModulesCheckClasspath(volmLibCoordinate)
builtinModulesCheckClasspath(libs.gson)
}
def builtinModulesJar = tasks.register('builtinModulesJar', JavaExec) {
group = 'build'
description = "Checks IrisModule's ${builtinModulesJarName} against the VolmLib classes the Bukkit jar leaves out and writes" +
" it to build/builtin-modules for bundling."
FileCollection built = configurations.builtinModules
classpath = configurations.builtinModulesCheckClasspath
mainClass.set('com.volmit.host.ModuleJarCheck')
inputs.files(built)
inputs.file(volmLibLeftOutFile)
outputs.file(bundledBuiltinModulesJar)
argumentProviders.add({
[built.singleFile.absolutePath, "--left-out=${volmLibLeftOutFile.absolutePath}".toString()] + builtinExposedPackages
} as CommandLineArgumentProvider)
ignoreExitValue = true
ByteArrayOutputStream problems = new ByteArrayOutputStream()
errorOutput = problems
doFirst {
// A jar from an earlier run that passed must not survive a run that fails.
bundledBuiltinModulesJar.get().asFile.delete()
}
doLast {
if (executionResult.get().exitValue != 0) {
throw new GradleException("The built-in modules jar uses what the Bukkit jar leaves out:\n" + problems.toString().trim() +
"\nUse another VolmLib class in IrisModule, or ship this one (core/${volmLibLeftOutFile.name}).")
}
java.nio.file.Files.copy(built.singleFile.toPath(), bundledBuiltinModulesJar.get().asFile.toPath())
}
}
// The class entries of the bundled jar. Those classes load from it only, in each pack's class loader, so the plugin leaves
// the module artifact's copies out.
Set<String> builtinJarClassEntries = null
Closure<Boolean> inBuiltinModulesJar = { FileTreeElement element ->
if (builtinJarClassEntries == null) {
builtinJarClassEntries = new java.util.zip.ZipFile(bundledBuiltinModulesJar.get().asFile).withCloseable { java.util.zip.ZipFile jar ->
jar.entries().toList().collect { it.name }.findAll { it.endsWith('.class') }.toSet()
}
}
builtinJarClassEntries.contains(element.relativePath.pathString)
}
tasks.named('test').configure {
inputs.files(builtinModulesJar)
systemProperty('iris.builtinModulesJar', bundledBuiltinModulesJar.get().asFile.absolutePath)
}
tasks.named('jar', Jar).configure {
from(builtinModulesJar)
}
tasks.named('shadowJar', com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar).configure {
dependsOn(embeddedAgentJar)
exclude(inBuiltinModulesJar)
from(builtinModulesJar)
mergeServiceFiles()
// minimize() stays off. Caffeine reaches its 520 generated cache and node classes through
// MethodHandles.Lookup.findClass on a computed name, and the VolmLib command, GUI and hotload
// surfaces are only referenced from :adapters:bukkit:plugin, which is merged into the artifact
// after this task runs. Both would be stripped as unreachable. Excluding them from minimization
// leaves it reaching ~25KB of Gson internals, which is not worth a mode that fails silently.
relocate('com.dfsek.paralithic', "${lib}.paralithic")
relocate('io.github.slimjar', "${lib}.slimjar")
exclude('modules/loader-agent.isolated-jar')
exclude(irisPackagesLeftOut)
exclude(irisClassesLeftOutEntries)
exclude(volmLibLeftOutEntries)
exclude(annotationOnlyArtifacts)
exclude(dependencyBuildMetadata)
from(embeddedAgentJar.map { it.archiveFile }) {
rename { String ignored -> 'agent.jar' }
}
}
rootProject.tasks.matching {
it.name == 'prepareKotlinBuildScriptModel'
}.configureEach {
dependsOn(generateTemplates)
}
sourceSets {
main {
java {
srcDir(generateTemplates.map { it.outputs })
}
}
}
tasks.register('bukkitPurityRatchet') {
group = 'verification'
description = 'Checks host Bukkit imports against the existing purity ceiling.'
File allowlistFile = project.file('purity-allowlist.txt')
File sourceRoot = project.file('src/main/java')
inputs.file(allowlistFile)
inputs.dir(sourceRoot)
doLast {
Set<String> allowed = allowlistFile.readLines().findAll { String line -> !line.isBlank() }.toSet()
List<String> offenders = new ArrayList<>()
List<String> coupled = new ArrayList<>()
sourceRoot.eachFileRecurse { File f ->
if (!f.name.endsWith('.java')) {
return
}
if (f.text.contains('org.bukkit')) {
String rel = sourceRoot.toPath().relativize(f.toPath()).toString()
coupled.add(rel)
if (!allowed.contains(rel)) {
offenders.add(rootProject.projectDir.toPath().relativize(f.toPath()).toString())
}
}
}
if (!offenders.isEmpty()) {
throw new GradleException("Bukkit purity ratchet violated - new org.bukkit coupling in:\n " + offenders.join('\n ') + "\nDecouple these files or (only with strong justification) add them to core/purity-allowlist.txt")
}
int shrunk = allowed.size() - coupled.size()
if (shrunk > 0) {
println("Purity ratchet: " + coupled.size() + " coupled files (" + shrunk + " fewer than allowlist - consider tightening core/purity-allowlist.txt)")
} else {
println("Purity ratchet: " + coupled.size() + " coupled files (at allowlist ceiling)")
}
}
}
tasks.named('check').configure {
dependsOn('bukkitPurityRatchet')
}