Skip to content
This repository has been archived by the owner on Jun 19, 2021. It is now read-only.

Commit

Permalink
Updated Upstream and Sidestream(s) (Paper/Tuinity/Airplane/Purpur/Emp…
Browse files Browse the repository at this point in the history
…irecraft) (#443)

* Updated Upstream and Sidestream(s) (Paper/Tuinity/Airplane/Purpur/Empirecraft)

Upstream/An Sidestream has released updates that appears to apply and compile correctly
This update has NOT been tested by YatopiaMC and as with ANY update, please do your own testing.

Paper Changes:
0641de2d4 [CI-SKIP] Change some fields to textara (#5405)
98a34ea47 [CI-SKIP] 🚀 Upgrade to new form-based templates (#5278)
bca97a8f7 replace spaces in world key (touches #5397)
de94f6485 Refactor chat message composition (#5396)
e27f334bb [CI-SKIP] Fix makemcdevsrc.sh for nms relocations (#5389)
ae15e85da Updated Upstream (CraftBukkit)
26fe0ac5a Only set despawnTimer for Wandering Traders spawned by MobSpawnerTrader (#5391)
b748eb7b8 Fix VanillaMobGoalTest#testBukkitMap (#5390)
18dbbb578 [Auto] Updated Upstream (CraftBukkit)
fac9cc5d5 [CI-SKIP] Ignore .gitignore
087aa70e7 Deprecate ItemStack#setLore(List<String>) and ItemStack#getLore, add Component based alternatives
9889c651c apply fixup
c310f0a61 Updated Upstream (Bukkit/CraftBukkit)
f17560ab0 wtf is this t file -jmp
347f3a9b8 fix compile
700e9e6a5 rebase
cf4dc464a Revert de5f4e469...c270abe96
6870db613 script & POM fix
743c6533c Replace ** with * (BSD/macOS)
376d7b097 Don't remove the .java
fcb3fd42a Fix macOS/BSD support
8cfc05249 Link correctly
ba1031ca7 Rename work dir
c8d844ab7 Actually fix preloading this time
e62aa5e3e Fix class preloading
1c03cf898 It's mojang math, not minecraft math
1034873df Apply fixups
39b125771 Use revision file
956150da7 Welcome to 1.16.5-R0.2
ccb217c01 Change cache keys
0d217001c more work
f6d820f07 It compiles
0f78e9525 More work
1718f61bf Updated Upstream (CraftBukkit/Spigot)
b28d46114 Update scripts for NMS repackaging
d4532f7e7 bug #5373 - fix AsyncChatEvent not being posted when processing a legacy APCE continuation
522ae1c51 Replace all block states of a specified block (#5055)
1cda67118 [Auto] Updated Upstream (CraftBukkit)
8c74d3126 Updated Upstream (Bukkit) (#5359)
fd3c66a91 bug #5362 - correctly pass "render type" when registering a new scoreboard objective

Tuinity Changes:
9bdcb9b Delete work dir when running jar
6351d7c Updated Upstream (Paper)
932c199 Generate mc-dev correctly
bf3e737 Make packet limiter work from IDE
1686f38 Fix packet limiter config
f40f7b4 Update README.md styling (#264)
da1c3ac GH Actions Changes (#213)
5f325ec Updated Upstream (Paper)
0f83fe4 Updated Upstream (Paper)
44e8e5d Do not load extra radius of chunks when loading a single chunk
31f9cae Revert custom table implementation for blockstate states
9ac33d1 Be aware of entity teleports when chunk checking entities
18c7f3f Always set impulse for projectiles to true, even if hit event failed

Airplane Changes:
f94d399 Merge pull request #18 from notOM3GA/upstream/nms-repackage
0fc6226 Force build for Flare update
08439d6 Updated Upstream (Tuinity)
0f80443 Updated Upstream (Tuinity)
2f6cbdc More debug for plugins not shutting down tasks
12e1b61 Updated Upstream (Tuinity)
fc778d3 Update README.md
db6b0eb Merge pull request #16 from DeadSteve51/patch-2
b23bee3 Remove debug
8157e98 Config style, flare style, disable tracker by def
98d0b58 Updates to README

Purpur Changes:
75b07a0 Fix stack overflow on armorstand movement
f754a7b Sneak to bulk process composter
1362f49 Updated Upstream (Paper, Tuinity, & Airplane)
5bf8615 [ci-skip] Conflict on change for adventure deprecations
114b37b Add purpur.yml to Flare (#204)
c6dce38 forgot the crops
c004236 Configurable ravager griefable blocks list
766246a [ci-skip] remove duplicate patch
ac93477 Config to make Creepers explode on death (#201)
297181e Updated Upstream (Paper, Tuinity, & Airplane)
45b9a18 Config to disable Llama caravans (#203)
a99a83b Allow fully disabling farmland trampling
3aa4f68 Tick fluids config
0e34d59 Add missing imports :/
3dd9f46 Updated Upstream (Paper, Tuinity, & Airplane)

Empirecraft Changes:
1b579407 Improve importmcdev script and fix first server patch
f597a82e Update generatesources script
218f5298 Fix patches - imported files
847cf558 Updated Paper
d51410c3 Updated Paper
fb3301fd Fix bow entity ai speed/distance
dbde1dc4 Add isJoined boolean to fake players
a23317f7 Update Fake Player API - misc changes
a970b77f Updated Paper

* Updated Upstream and Sidestream(s) (Paper/Airplane/Purpur)

Upstream/An Sidestream has released updates that appears to apply and compile correctly
This update has NOT been tested by YatopiaMC and as with ANY update, please do your own testing.

Paper Changes:
7259c32ba [CI-SKIP] [Auto] Rebuild Patches
0e06e912e Fix annotations so Inventory#getContents returns non-null array with nullable type (#5350)
b90b4f8ad Properly apply Sign#isEditable to TEs when calling BlockState#update

Airplane Changes:
87d4a17 Track queue debug command

Purpur Changes:
d44f93e Fix tpsbar with naughty plugins

* Updated Upstream and Sidestream(s) (Purpur)

Upstream/An Sidestream has released updates that appears to apply and compile correctly
This update has NOT been tested by YatopiaMC and as with ANY update, please do your own testing.

Purpur Changes:
99f1ce6 Add enchantment target for bows and crossbows
af9181e Add configurable drowning settings (closes #221) (#222)
f72437b Remove mcdevimports.* (#228)
08de42d Add config for infinity on crossbows (#215)
5f76cb3 Add a config for villager trading (#210)
67ffa05 Add config for disabling skipping the night (#209)

* revert paper commit that made the build fail (CI still doesn't work)

* Update build.yml

* test2

* Update build.yml

* take7

* how often does md_5 change mappings?

this will come back to bite me in exactly 17 days

* Revert "how often does md_5 change mappings?"

This reverts commit 8b05c16.

* Updated Upstream and Sidestream(s) (Paper/Purpur)

Upstream/An Sidestream has released updates that appears to apply and compile correctly
This update has NOT been tested by YatopiaMC and as with ANY update, please do your own testing.

Paper Changes:
6caa330c6 Add checkerframework nullness annotations to accepted list for AnnotationTest (#5409)

Purpur Changes:
96f5360 Config to allow for unsafe enchants (#235)
b6235af Rebase on latest Purpur (#230)
754948e Updated Upstream (Paper)
f55c0e9 Option to make doors require redstone (closes #171)
34d5818 Fix paper using wrong annotations
f31bcc6 Updated Upstream (Paper & Airplane)
55244dd Config to show Armor Stand arms on spawn (#231)
c726479 Config to disable hostile mob spawn on ice `:)` (closes #214) (#229)
26a0094 Break individual slabs when sneaking (closes #218)
c3de3ac Fix wart farmers plating vegetables on soul sand

* Updated Upstream and Sidestream(s) (Tuinity/Purpur)

Upstream/An Sidestream has released updates that appears to apply and compile correctly
This update has NOT been tested by YatopiaMC and as with ANY update, please do your own testing.

Tuinity Changes:
1b0d783 Updated Upstream (Paper)
2c16629 Fix NPE in NetworkManager#execute

Purpur Changes:
0d25d39 Add cache for slime max health (resolves #234)
39dd78a Fix #240 - Separate slab breaking triggers every single time
1ecb9ef Projectile offsets config (#237)
33ee1e7 Configurable sponge absorption (closes #232) (#236)
a0355eb Add Note Block to disabled block updates (#241)

* Updated Upstream and Sidestream(s) (Paper)

Upstream/An Sidestream has released updates that appears to apply and compile correctly
This update has NOT been tested by YatopiaMC and as with ANY update, please do your own testing.

Paper Changes:
8b47131da Optimize short circuit evaluation of sign check (#5348)
1a2fd12a5 Drop carried item when player has disconnected (#5036) (#5166)
68af93524 Use PaperAdventure.PLAIN instead of PlainComponentSerializer.plain() for AdventureComponent#getString (#5414)

* Updated Upstream and Sidestream(s) (Tuinity/Purpur)

Upstream/An Sidestream has released updates that appears to apply and compile correctly
This update has NOT been tested by YatopiaMC and as with ANY update, please do your own testing.

Tuinity Changes:
94f025a Updated Upstream (Paper)
ab00f31 Do not load chunks around fake players
a9599d8 Fix incorrect parsing of positive target-send-rate
2a6cd81 Make sure to remove correct TE during TE tick

Purpur Changes:
9dfc780 Config for powered rail activation distance (#248)

Co-authored-by: duplexsystem <[email protected]>
  • Loading branch information
Titaniumtown and duplexsystem authored Mar 28, 2021
1 parent 9168211 commit ac524e3
Show file tree
Hide file tree
Showing 401 changed files with 17,008 additions and 12,619 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ on:

jobs:
build:

runs-on: ubuntu-latest

strategy:
Expand Down Expand Up @@ -59,7 +58,7 @@ jobs:
id: decompile-cache
with:
path: Paper/work/Minecraft/${{ steps.mcver.outputs.mcver }}
key: ${{ steps.mcver.outputs.mcver }}-${{ runner.os }}-java-${{ matrix.java }}-minecraft-decomp
key: ${{ hashFiles('Paper/work/BuildData/mappings/bukkit-$STEPS_MCVER_OUTPUTS_MCVER-cl.csrg') }}-${{ steps.mcver.outputs.mcver }}-${{ runner.os }}-java-${{ matrix.java }}-minecraft-decomp

- name: Apply Patches
run: |
Expand Down
95 changes: 60 additions & 35 deletions PATCHES.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Paper
Submodule Paper updated 685 files
22 changes: 14 additions & 8 deletions buildSrc/src/main/kotlin/ConfigureSubprojects.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import com.github.jengelman.gradle.plugins.shadow.ShadowPlugin
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
// import com.github.jengelman.gradle.plugins.shadow.transformers.Log4j2PluginsCacheFileTransformer
import xyz.jpenilla.toothpick.transformer.ModifiedLog4j2PluginsCacheFileTransformer
import transformer.ModifiedLog4j2PluginsCacheFileTransformer
import relocation.ToothpickRelocator
import kotlinx.dom.elements
import kotlinx.dom.parseXml
import kotlinx.dom.search
Expand Down Expand Up @@ -148,8 +149,7 @@ private fun Project.configureServerProject() {
destination = project.buildDir.resolve("tmp/pom.xml")
}

@Suppress("UNUSED_VARIABLE")
val test by tasks.getting(Test::class) {
tasks.withType<Test> {
// didn't bother to look into why these fail. paper excludes them in paperweight as well though
exclude("org/bukkit/craftbukkit/inventory/ItemStack*Test.class")
}
Expand All @@ -158,7 +158,6 @@ private fun Project.configureServerProject() {
archiveClassifier.set("") // ShadowJar is the main server artifact
dependsOn(generatePomFileForMavenJavaPublication)
transform(ModifiedLog4j2PluginsCacheFileTransformer::class.java)
//transform(Log4j2PluginsCacheFileTransformer::class.java)
mergeServiceFiles()
manifest {
attributes(
Expand All @@ -182,7 +181,6 @@ private fun Project.configureServerProject() {
relocate("org.bukkit.craftbukkit", "org.bukkit.craftbukkit.v${toothpick.nmsPackage}") {
exclude("org.bukkit.craftbukkit.Main*")
}
relocate("net.minecraft.server", "net.minecraft.server.v${toothpick.nmsPackage}")
relocationSet.add(PatchesMetadata.Relocation("", "net.minecraft.server.v${toothpick.nmsPackage}", false))

// Make sure we relocate deps the same as Paper et al.
Expand All @@ -202,9 +200,17 @@ private fun Project.configureServerProject() {
.elements("relocation").forEach { relocation ->
val pattern = relocation.search("pattern").first().textContent
val shadedPattern = relocation.search("shadedPattern").first().textContent
if (pattern != "org.bukkit.craftbukkit" && pattern != "net.minecraft.server") { // We handle these ourselves above
logger.debug("Imported relocation to server project shadowJar from ${pomFile.absolutePath}: $pattern to $shadedPattern")
relocate(pattern, shadedPattern)
val rawString = relocation.search("rawString").firstOrNull()?.textContent?.toBoolean() ?: false
if (pattern != "org.bukkit.craftbukkit") { // We handle cb ourselves
val excludes = if (rawString) listOf("net/minecraft/data/Main*") else emptyList()
relocate(
ToothpickRelocator(
pattern,
shadedPattern.replace("\${minecraft_version}", toothpick.nmsPackage),
rawString,
excludes = excludes
)
)
relocationSet.add(PatchesMetadata.Relocation(pattern, shadedPattern, true))
}
}
Expand Down
1 change: 1 addition & 0 deletions buildSrc/src/main/kotlin/InitTasks.kt
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,5 @@ internal fun Project.initToothpickTasks() {

val upstreamCommit = createUpstreamCommitTask()

val repackageNMS = createRepackageNMSTask()
}
5 changes: 4 additions & 1 deletion buildSrc/src/main/kotlin/ToothpickExtension.kt
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,12 @@ open class ToothpickExtension(objects: ObjectFactory) {
}
}

val paperWorkDir: File
val paperDecompDir: File
get() = paperDir.resolve("work/Minecraft/${minecraftVersion}")

val paperWorkDir: File
get() = paperDir.resolve("work")

fun getUpstreams(rootProjectDir: File): MutableList<Upstream>? {
val configDir = rootProjectDir.resolve("$rootProjectDir/upstreamConfig")
val upstreams = configDir.listFiles()
Expand Down
20 changes: 12 additions & 8 deletions buildSrc/src/main/kotlin/Util.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ data class CmdResult(val exitCode: Int, val output: String?)
fun Project.cmd(
vararg args: String,
dir: File = rootProject.projectDir,
printOut: Boolean = false
printOut: Boolean = false,
environment: Map<String, String> = emptyMap()
): CmdResult {
val process = ProcessBuilder()
.command(*args)
.redirectErrorStream(true)
.directory(dir)
.start()
val process = ProcessBuilder().apply {
command(*args)
redirectErrorStream(true)
directory(dir)
environment().putAll(environment)
}.start()
val output = process.inputStream.bufferedReader().use { reader ->
reader.lines().asSequence()
.onEach {
Expand Down Expand Up @@ -46,14 +48,16 @@ fun ensureSuccess(
fun Project.gitCmd(
vararg args: String,
dir: File = rootProject.projectDir,
printOut: Boolean = false
printOut: Boolean = false,
environment: Map<String, String> = emptyMap()
): CmdResult =
cmd("git", *args, dir = dir, printOut = printOut)

fun Project.bashCmd(
vararg args: String,
dir: File = rootProject.projectDir,
printOut: Boolean = false
printOut: Boolean = false,
environment: Map<String, String> = emptyMap()
): CmdResult =
cmd("bash", "-c", *args, dir = dir, printOut = printOut)

Expand Down
58 changes: 58 additions & 0 deletions buildSrc/src/main/kotlin/relocation/ToothpickRelocator.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* This file is part of Toothpick, licensed under the MIT License.
*
* Copyright (c) 2020-2021 Jason Penilla & Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package relocation

import com.github.jengelman.gradle.plugins.shadow.relocation.Relocator
import com.github.jengelman.gradle.plugins.shadow.relocation.SimpleRelocator
import java.lang.reflect.Method
import java.util.regex.Pattern

internal class ToothpickRelocator(
pattern: String,
shadedPattern: String,
rawString: Boolean = false,
includes: List<String> = emptyList(),
excludes: List<String> = emptyList(),
private val simpleRelocator: SimpleRelocator = SimpleRelocator(pattern, shadedPattern, includes, excludes, rawString)
) : Relocator by simpleRelocator {
override fun canRelocatePath(path: String): Boolean {
// Respect includes/excludes for rawString too
if (simpleRelocator.rawString) {
return isIncludedMethod(simpleRelocator, path) as Boolean
&& !(isExcludedMethod(simpleRelocator, path) as Boolean)
&& Pattern.compile(simpleRelocator.pathPattern).matcher(path).find()
}
return simpleRelocator.canRelocatePath(path)
}

companion object {
private val isExcludedMethod: Method = SimpleRelocator::class.java.getDeclaredMethod("isExcluded", String::class.java)
private val isIncludedMethod: Method = SimpleRelocator::class.java.getDeclaredMethod("isIncluded", String::class.java)

init {
isExcludedMethod.isAccessible = true
isIncludedMethod.isAccessible = true
}
}
}
64 changes: 43 additions & 21 deletions buildSrc/src/main/kotlin/task/ImportMCDev.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import org.gradle.api.Task
import toothpick
import upstreams
import java.io.File
import java.nio.file.Files
import kotlin.streams.toList

internal fun Project.createImportMCDevTask(
receiver: Task.() -> Unit = {}
Expand All @@ -20,42 +22,62 @@ internal fun Project.createImportMCDevTask(
val upstreamServer = toothpick.serverProject.baseDir
val importLog = arrayListOf("Extra mc-dev imports")

fun isDuplicateImport(target: File, className: String): Boolean {
if (!target.exists()) return false
val message = "Skipped import for $className, a class with that name already exists in the source tree. Is there an extra entry in mcdevimports.json?"
project.gradle.taskGraph.allTasks.last().doLast {
logger.warn(message)
}
logger.warn(message)
return true
}

fun importNMS(className: String) {
logger.lifecycle("Importing n.m.s.$className")
importLog.add("Imported n.m.s.$className")
val source = toothpick.paperWorkDir.resolve("spigot/net/minecraft/server/$className.java")
logger.lifecycle("Importing $className")
val classPath = "${className.replace(".", "/")}.java"
val source = toothpick.paperDecompDir.resolve("spigot/$classPath")
importLog.add("Importing $className")
if (!source.exists()) error("Missing NMS: $className")
val target = upstreamServer.resolve("src/main/java/net/minecraft/server/$className.java")
val target = upstreamServer.resolve("src/main/java/$classPath")
if (isDuplicateImport(target, className)) return
target.parentFile.mkdirs()
source.copyTo(target)
}

fun importLibrary(import: LibraryImport) {
val (group, lib, prefix, file) = import
logger.lifecycle("Importing $group.$lib $prefix/$file")
importLog.add("Imported $group.$lib $prefix/$file")
val source = toothpick.paperWorkDir.resolve("libraries/$group/$lib/$prefix/$file.java")
val className = "${prefix.replace("/", ".")}.$file"
importLog.add("Imported $className from $group.$lib")
logger.lifecycle("Importing $className from $group.$lib")
val source = toothpick.paperDecompDir.resolve("libraries/$group/$lib/$prefix/$file.java")
if (!source.exists()) error("Missing Base: $lib $prefix/$file")
val targetDir = upstreamServer.resolve("src/main/java/$prefix")
val target = targetDir.resolve("$file.java")
if (isDuplicateImport(target, className)) return
targetDir.mkdirs()
source.copyTo(target)
}

fun findNeededImports(patches: List<File>): Set<String> = patches.asSequence()
.flatMap { it.readLines().asSequence() }
.filter { line ->
line.startsWith("+++ b/src/main/java/net/minecraft/")
|| line.startsWith("+++ b/src/main/java/com/mojang/math/")
}
.distinct()
.map { it.substringAfter("+++ b/src/main/java/") }
.filter { !upstreamServer.resolve("src/main/java/$it").exists() }
.filter {
val sourceFile = toothpick.paperDecompDir.resolve("spigot/$it")
val exists = sourceFile.exists()
if (!sourceFile.exists()) logger.lifecycle("$it is either missing, or is a new file added through a patch")
exists
}
.map { it.replace("/", ".").substringBefore(".java") }
.toSet()

fun getAndApplyNMS(patchesDir: File) {
(patchesDir.listFiles() ?: return).asSequence()
.flatMap { it.readLines().asSequence() }
.filter { it.startsWith("+++ b/src/main/java/net/minecraft/server/") }
.distinct()
.map { it.substringAfter("/server/").substringBefore(".java") }
.filter { !upstreamServer.resolve("src/main/java/net/minecraft/server/$it.java").exists() }
.map { toothpick.paperWorkDir.resolve("spigot/net/minecraft/server/$it.java") }
.filter {
val exists = it.exists()
if (!it.exists()) logger.lifecycle("NMS ${it.nameWithoutExtension} is either missing, or is a new file added through a patch")
exists
}
.map { it.nameWithoutExtension }
.forEach(::importNMS)
findNeededImports(patchesDir.listFiles().toList()).toList().forEach(::importNMS)
}

doLast {
Expand Down
108 changes: 108 additions & 0 deletions buildSrc/src/main/kotlin/task/RepackageNMS.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* This file is part of Toothpick, licensed under the MIT License.
*
* Copyright (c) 2020-2021 Jason Penilla & Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package task

import org.gradle.api.tasks.TaskAction
import java.io.File
import org.gradle.api.Project
import org.gradle.api.Task
import taskGroup
import upstreams
import gitCmd
import toothpick
import java.nio.file.Paths
import java.util.concurrent.ConcurrentHashMap
import ensureSuccess
import java.net.URL

@Suppress("UNUSED_VARIABLE")
internal fun Project.createRepackageNMSTask(
receiver: Task.() -> Unit = {}
): Task = tasks.create("repackageNMS") {
receiver(this)
group = taskGroup
class Mapping(fullyQualifiedClassName: String) {
val className = fullyQualifiedClassName.substringAfterLast(".")
val oldFQName = "net.minecraft.server.$className"
val oldJavaFileName = "net/minecraft/server/$className.java"
val newFQName = fullyQualifiedClassName
val newJavaFileName = "${fullyQualifiedClassName.replace(".", "/")}.java"
}

class Remapper(private val mappings: Set<Mapping>) {
fun remapFile(file: File): String =
file.readLines().joinToString("\n") { remapLine(it) } + "\n"

private fun remapLine(line: String): String {
if (
line.startsWith("diff --git ")
|| line.startsWith("+++ ")
|| line.startsWith("--- ")
) {
var text = line
mappings.forEach { text = text.replace(it.oldJavaFileName, it.newJavaFileName) }
return text
}
if (line.startsWith("+")) {
var text = line
mappings.forEach { text = text.replace(it.oldFQName, it.newFQName) }
return text
}
return line
}
}
doLast {
logger.lifecycle("Downloading class mappings from spigot...")
val mappingsFileText = URL("https://hub.spigotmc.org/stash/projects/SPIGOT/repos/builddata/raw/mappings/bukkit-1.16.5-cl.csrg?at=80d35549ec67b87a0cdf0d897abbe826ba34ac27").readText()
logger.lifecycle("Done downloading class mappings.")

logger.lifecycle(">>> Preparing patches for NMS repackage")
val mappings = mappingsFileText
.split("\n")
.asSequence()
.filter { !it.startsWith("#") && !it.contains("$") && it.trim().isNotEmpty() }
.map { it.split(" ")[1].replace("/", ".") }
.map { Mapping(it) }
.filter { it.newFQName != it.oldFQName }
.toSet()
val remapper = Remapper(mappings)

toothpick.subprojects.values
.map { it.patchesDir }
.forEach { patchesDir ->
val repackagedPatchesDir =
patchesDir.parentFile.resolve("${patchesDir.name}_repackaged-${System.currentTimeMillis()}")
repackagedPatchesDir.mkdir()
val patchFiles = patchesDir.listFiles()?.toList() ?: error("Could not list patch files")
patchFiles.parallelStream().forEach { patch ->
logger.lifecycle("Processing ${patchesDir.name}/${patch.name}...")
val newPatch = repackagedPatchesDir.resolve(patch.name)
newPatch.writeText(remapper.remapFile(patch))
}
}

logger.lifecycle(">>> Done preparing patches")
}
}

Loading

0 comments on commit ac524e3

Please sign in to comment.