Skip to content

Commit

Permalink
add jar compressing and stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
rhysdh540 committed Jul 16, 2024
1 parent ab1190b commit e981ef7
Show file tree
Hide file tree
Showing 4 changed files with 206 additions and 24 deletions.
119 changes: 95 additions & 24 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
@file:Suppress("UnstableApiUsage")

import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import xyz.wagyourtail.unimined.api.minecraft.task.RemapJarTask
import xyz.wagyourtail.unimined.expect.task.ExpectPlatformJar
import xyz.wagyourtail.unimined.internal.minecraft.task.RemapJarTaskImpl
Expand Down Expand Up @@ -29,8 +31,12 @@ allprojects {
group = "maven_group"()

java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
toolchain {
languageVersion.set(JavaLanguageVersion.of("java_version"()))
}

sourceCompatibility = JavaVersion.toVersion("java_version"())
targetCompatibility = JavaVersion.toVersion("java_version"())
}

idea.module.setDownloadSources(true)
Expand Down Expand Up @@ -59,11 +65,11 @@ allprojects {

tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
options.release = 17
options.release = "java_version"().toInt()
options.compilerArgs.addAll(listOf("-Xplugin:Manifold no-bootstrap", "-implicit:none"))

javaCompiler = javaToolchains.compilerFor {
languageVersion.set(JavaLanguageVersion.of(17))
languageVersion.set(JavaLanguageVersion.of("java_version"()))
}
}

Expand Down Expand Up @@ -131,7 +137,7 @@ subprojects {

tasks.jar {
archiveClassifier = "$platform-dev-unmapped"
destinationDirectory.set(layout.buildDirectory.dir("devlibs"))
putInDevlibs()
}

val common by configurations.registering
Expand All @@ -144,25 +150,43 @@ subprojects {
archiveBaseName.set("archives_base_name"())
archiveVersion.set("modVersion"())
archiveClassifier.set("$platform-unmapped")
destinationDirectory.set(layout.buildDirectory.dir("devlibs"))
putInDevlibs()

configurations = listOf(common.get())
relocate("dev.rdh.createunlimited.$platform", "dev.rdh.createunlimited")

relocate("dev.rdh.createunlimited.${project.name}", "dev.rdh.createunlimited.${project.name}.platform")
relocate("dev.rdh.createunlimited", "dev.rdh.createunlimited.${project.name}")
configurations = listOf(common.get())
}

val expectPlatformJar by tasks.register<ExpectPlatformJar>("platformJar") {
group = "unimined"
platformName = platform
archiveClassifier = "expect-$platform"
putInDevlibs()
inputFiles = files(tasks.shadowJar.get().archiveFile)
}

tasks.register<RemapJarTaskImpl>("remapPlatformJar", unimined.minecrafts[sourceSets["main"]]).configure {
dependsOn("shadowJar")
val remapPlatformJar = tasks.register<RemapJarTaskImpl>("remapPlatformJar", unimined.minecrafts[sourceSets["main"]])
remapPlatformJar.configure {
dependsOn(expectPlatformJar)
inputFile.set(expectPlatformJar.archiveFile)
archiveClassifier = platform
}

tasks.register<ShadowJar>("preShadow") {
from(zipTree(remapPlatformJar.get().archiveFile)) {
rename {
if(it == "createunlimited.mixins.json") "createunlimited-$platform.mixins.json"
else if(it.endsWith(".jar")) it + "_"
else it
}
includeEmptyDirs = false
}

archiveClassifier.set("premerge-$platform")
putInDevlibs()

relocate("dev.rdh.createunlimited", "dev.rdh.createunlimited.${project.name}")
}
}

tasks.jar { enabled = false }
Expand Down Expand Up @@ -201,14 +225,62 @@ dependencies {
implementation("org.spongepowered:mixin:${"mixin_version"()}")
}

val mergeJars = tasks.register<ShadowJar>("mergeJars") {
val mergeJars by tasks.register<Jar>("mergeJars") {
group = "build"
description = "Merges the platform shadow jars into a single jar"
archiveBaseName.set("archives_base_name"())
archiveVersion.set("modVersion"())
subprojects.map { it.tasks["remapPlatformJar"] }.forEach {
dependsOn(it)
from(it)
archiveBaseName = "archives_base_name"()
archiveVersion = "modVersion"()
archiveClassifier = "almost-done"
putInDevlibs()

includeEmptyDirs = false
duplicatesStrategy = DuplicatesStrategy.EXCLUDE

val oldMixinConfig = "createunlimited.mixins.json"
fun newMixinConfig(platform: String) = "createunlimited-$platform.mixins.json"

val oldMixinPackage = "dev.rdh.createunlimited.asm"
fun newMixinPackage(platform: String) = "dev.rdh.createunlimited.$platform.asm"

from(zipTree(project(":fabric").tasks.get<ShadowJar>("preShadow").archiveFile)) {
includeEmptyDirs = false
val newMixinConfig = newMixinConfig("fabric")
val newMixinPackage = newMixinPackage("fabric")

filesMatching("fabric.mod.json") {
filter { it.replace(oldMixinConfig, newMixinConfig) }
}
filesMatching(newMixinConfig) {
filter { it.replace(oldMixinPackage, newMixinPackage) }
}
}

from(zipTree(project(":forge").tasks.get<ShadowJar>("preShadow").archiveFile)) {
includeEmptyDirs = false
filesMatching(newMixinConfig("forge")) {
filter { it.replace(oldMixinPackage, newMixinPackage("forge")) }
}

rename { if(it.endsWith(".jar_")) it.substring(0, it.length - 1) else it }
}

manifest {
attributes["MixinConfigs"] = newMixinConfig("forge")
attributes["Fabric-Loom-Mixin-Remap-Type"] = "static"
}
}

val compressJar = tasks.register<ProcessJar>("compressJar") {
input.set(mergeJars.archiveFile)
description = "Compresses the merged jar"

archiveBaseName = "archives_base_name"()
archiveVersion = "modVersion"()
archiveClassifier = ""

addFileProcessor("json", "mcmeta") { file ->
val json = JsonSlurper().parse(file)
file.outputStream().write(JsonOutput.toJson(json).toByteArray())
}
}

Expand All @@ -217,7 +289,7 @@ tasks.assemble {
}

fun setup() {
println("Create Unlimited v${"mod_version"()}")
println("${project.name} v${"mod_version"()}")

val buildNumber: String? = System.getenv("GITHUB_RUN_NUMBER")
if(buildNumber != null) {
Expand All @@ -234,15 +306,14 @@ fun setup() {
println("Current commit: ${git.hash()}")
if (git.isDirty()) {
var changes = git.getUncommitedChanges().split("\n").toMutableList()
val maxChanges = 10
if (changes.size > maxChanges) {
val size = changes.size
val maxChanges = "git_max_changes"().toInt()
if (size > maxChanges) {
changes = changes.subList(0, maxChanges)
changes.add("... and ${changes.size - maxChanges} more")
changes.add("... and ${size - maxChanges} more")
}

changes.replaceAll { " - $it" }

println("Uncommitted changes:\n${changes.joinToString("\n")}")
println("Uncommitted changes:\n${changes.map{ " - $it" }.joinToString("\n")}")
}
} else {
println("No git repository")
Expand Down
86 changes: 86 additions & 0 deletions buildSrc/src/main/kotlin/compress.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import org.gradle.api.tasks.InputFile
import org.gradle.jvm.tasks.Jar
import java.io.File
import java.util.jar.JarEntry
import java.util.jar.JarOutputStream
import java.util.zip.Deflater

typealias FileProcessor = (File) -> Unit

open class ProcessJar : Jar() {
val input = project.objects.fileProperty()
@InputFile get

private val processors = mutableListOf<FileProcessor>()

init {
group = "build"
}

fun addFileProcessor(regex: Regex, processor: FileProcessor) {
processors.add {
it.walkTopDown().forEach { file ->
if (file.extension.matches(regex))
processor(file)
}
}
}

fun addFileProcessor(vararg extensions: String, processor: FileProcessor) {
processors.add {
it.walkTopDown().forEach { file ->
if (file.extension in extensions)
processor(file)
}
}
}

fun addDirProcessor(processor: FileProcessor) {
processors.add(processor)
}

override fun copy() {
val inputJar = input.get().asFile

if (!inputJar.exists())
error("Input jar does not exist: $inputJar")

val dir = temporaryDir.resolve("unpack")

if (dir.exists())
dir.deleteRecursively()
dir.mkdirs()

// unpack jar to temp dir
project.copy {
from(project.zipTree(inputJar))
into(dir)
}

processors.forEach { it(dir) }

// merge manifests
val manifestFile = dir.resolve("META-INF/MANIFEST.MF")
if (manifestFile.exists()) {
manifest.from(manifestFile)
manifestFile.delete()
manifestFile.createNewFile()
manifest.effectiveManifest.writeTo(manifestFile)
}

// repack jar
JarOutputStream(archiveFile.get().asFile.outputStream()).use { jos ->
jos.setLevel(Deflater.BEST_COMPRESSION)
for (it in dir.walkTopDown()) {
if(it.isDirectory) continue
val entry = JarEntry(it.relativeTo(dir).path)
jos.putNextEntry(entry)
it.inputStream().copyTo(jos)
jos.closeEntry()
}

jos.finish()
jos.flush()
}
}
}
23 changes: 23 additions & 0 deletions buildSrc/src/main/kotlin/util.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import org.gradle.api.Task
import org.gradle.api.internal.file.copy.DefaultCopySpec
import org.gradle.api.tasks.AbstractCopyTask
import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.bundling.AbstractArchiveTask
import org.gradle.jvm.tasks.Jar

fun Jar.clearSourcePaths() {
AbstractCopyTask::class.java.getDeclaredField("mainSpec").let {
it.isAccessible = true
val thing = it.get(this) as DefaultCopySpec
thing.sourcePaths.clear()
it.isAccessible = false
}
}

fun AbstractArchiveTask.putInDevlibs() {
destinationDirectory.set(project.layout.buildDirectory.dir("devlibs"))
}

inline fun <reified T : Task> TaskContainer.get(name: String): T {
return this.withType(T::class.java).getByName(name)
}
2 changes: 2 additions & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ org.gradle.caching = true
# configuration
strip_lvts = true
mixin.debug = true
git_max_changes = 10

# gradle plugin versions
shadow_version = 8.1.1
Expand All @@ -23,6 +24,7 @@ maven_group = dev.rdh
archives_base_name = createunlimited

# common dependencies
java_version = 17
fabric_version = 0.15.11
manifold_version = 2024.1.20
mixin_version = 0.8.5
Expand Down

0 comments on commit e981ef7

Please sign in to comment.