Compare commits

..

1 commit

Author SHA1 Message Date
Jason Penilla
7d6c9738e3
Initial support for remapping bundled libraries 2023-12-12 21:58:16 -08:00
157 changed files with 556 additions and 1231 deletions

View file

@ -3,7 +3,3 @@ tasks.register("printVersion") {
println(version)
}
}
tasks.wrapper {
distributionType = Wrapper.DistributionType.ALL
}

View file

@ -1,5 +1,6 @@
import com.diffplug.gradle.spotless.SpotlessExtension
import net.kyori.indra.licenser.spotless.IndraSpotlessLicenserExtension
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
idea
@ -10,21 +11,9 @@ java {
withSourcesJar()
}
tasks.withType(JavaCompile::class).configureEach {
options.release = 11
}
kotlin {
jvmToolchain {
languageVersion = JavaLanguageVersion.of(17)
}
target {
compilations.configureEach {
kotlinOptions {
jvmTarget = "11"
freeCompilerArgs = listOf("-Xjvm-default=all", "-Xjdk-release=11")
}
}
languageVersion.set(JavaLanguageVersion.of(11))
}
}
@ -41,7 +30,14 @@ repositories {
}
}
mavenCentral()
gradlePluginPortal()
}
configurations.all {
if (name == "compileOnly") {
return@all
}
dependencies.remove(project.dependencies.gradleApi())
dependencies.removeIf { it.group == "org.jetbrains.kotlin" }
}
dependencies {
@ -60,12 +56,11 @@ testing {
}
}
configurations.all {
if (name == "compileOnly") {
return@all
tasks.withType<KotlinCompile> {
kotlinOptions {
jvmTarget = "11"
freeCompilerArgs = listOf("-Xjvm-default=all")
}
dependencies.remove(project.dependencies.gradleApi())
dependencies.removeIf { it.group == "org.jetbrains.kotlin" }
}
tasks.jar {

View file

@ -35,7 +35,7 @@ fun ShadowJar.configureStandard() {
val sourcesJar by tasks.existing(AbstractArchiveTask::class) {
from(
zipTree(project(":nugget-lib").tasks
zipTree(project(":paperweight-lib").tasks
.named("sourcesJar", AbstractArchiveTask::class)
.flatMap { it.archiveFile })
) {
@ -43,15 +43,15 @@ val sourcesJar by tasks.existing(AbstractArchiveTask::class) {
}
}
val prefix = project.name.substringAfter("nugget-")
val prefix = project.name.substringAfter("paperweight-")
gradlePlugin {
website.set("https://git.zontreck.com/ObsidianMC/nugget")
vcsUrl.set("https://git.zontreck.com/ObsidianMC/nugget")
plugins.create("nugget-$prefix") {
website.set("https://github.com/PaperMC/paperweight")
vcsUrl.set("https://github.com/PaperMC/paperweight")
plugins.create("paperweight-$prefix") {
id = "io.papermc.paperweight." + prefix
displayName = "nugget $prefix"
tags.set(listOf("obsidian", "minecraft"))
displayName = "paperweight $prefix"
tags.set(listOf("paper", "minecraft"))
}
}
@ -64,7 +64,7 @@ val shadowJar by tasks.existing(ShadowJar::class) {
return@existing
}
val prefix = "obsidian.libs"
val prefix = "paper.libs"
listOf(
"com.github.salomonbrys.kotson",
"com.google.errorprone.annotations",
@ -91,21 +91,11 @@ val shadowJar by tasks.existing(ShadowJar::class) {
}
}
val MAVEN_PASSWORD = "AriasCreationsMavenPassword"
val MAVEN_USER = "AriasCreationsMavenUser"
publishing {
repositories {
maven {
url = uri("https://git.zontreck.com/api/packages/ObsidianMC/maven")
name = "obsidian"
credentials {
username = project.findProperty(MAVEN_USER)?.toString()
password = project.findProperty(MAVEN_PASSWORD)?.toString()
}
maven("https://repo.papermc.io/repository/maven-snapshots/") {
credentials(PasswordCredentials::class)
name = "paper"
}
}
@ -119,11 +109,11 @@ publishing {
}
fun MavenPom.pomConfig() {
val repoPath = "ObsidianMC/nugget"
val repoUrl = "https://git.zontreck.com/$repoPath"
val repoPath = "PaperMC/paperweight"
val repoUrl = "https://github.com/$repoPath"
name.set("nugget")
description.set("Gradle plugin for the ObsidianMC project")
name.set("paperweight")
description.set("Gradle plugin for the PaperMC project")
url.set(repoUrl)
inceptionYear.set("2020")

View file

@ -1,5 +1,5 @@
group = com.zontreck.nugget
version = 1.7.4-SNAPSHOT
group = io.papermc.paperweight
version = 1.5.12-SNAPSHOT
org.gradle.caching = true
org.gradle.parallel = true

View file

@ -1,5 +1,5 @@
[versions]
asm = "9.7"
asm = "9.6"
lorenz = "0.5.8"
hypo = "1.2.4"
@ -16,7 +16,7 @@ cadix-lorenz-asm = { module = "org.cadixdev:lorenz-asm", version.ref = "lorenz"
cadix-lorenz-proguard = { module = "org.cadixdev:lorenz-io-proguard", version.ref = "lorenz" }
cadix-atlas = "org.cadixdev:atlas:0.2.1"
cadix-at = "org.cadixdev:at:0.1.0-rc1"
cadix-mercury = "org.cadixdev:mercury:0.1.2-paperweight-SNAPSHOT"
cadix-mercury = "org.cadixdev:mercury:0.1.1-paperweight-SNAPSHOT"
hypo-model = { module = "dev.denwav.hypo:hypo-model", version.ref = "hypo" }
hypo-core = { module = "dev.denwav.hypo:hypo-core", version.ref = "hypo" }
@ -35,7 +35,7 @@ diffpatch = "codechicken:DiffPatch:1.5.0.29"
gradle-licenser = "net.kyori:indra-licenser-spotless:3.1.3"
gradle-spotless = "com.diffplug.spotless:spotless-plugin-gradle:6.23.1"
gradle-shadow = "com.github.johnrengelman.shadow:com.github.johnrengelman.shadow.gradle.plugin:8.1.1"
gradle-kotlin-dsl = "org.gradle.kotlin.kotlin-dsl:org.gradle.kotlin.kotlin-dsl.gradle.plugin:4.3.0"
gradle-kotlin-dsl = "org.gradle.kotlin.kotlin-dsl:org.gradle.kotlin.kotlin-dsl.gradle.plugin:4.2.1"
gradle-plugin-kotlin = { module = "org.jetbrains.kotlin.jvm:org.jetbrains.kotlin.jvm.gradle.plugin" }
gradle-plugin-publish = "com.gradle.publish:plugin-publish-plugin:1.2.1"

Binary file not shown.

View file

@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME

20
gradlew.bat vendored
View file

@ -43,11 +43,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail

View file

@ -1,74 +0,0 @@
/*
* paperweight is a Gradle plugin for the PaperMC project.
*
* Copyright (c) 2023 Kyle Wood (DenWav)
* Contributors
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 only, no later versions.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.papermc.paperweight
import io.papermc.paperweight.extension.PaperweightSourceGeneratorExt
import io.papermc.paperweight.tasks.*
import io.papermc.paperweight.util.*
import io.papermc.paperweight.util.constants.*
import kotlin.io.path.*
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.*
abstract class PaperweightSourceGeneratorHelper : Plugin<Project> {
override fun apply(target: Project) = with(target) {
val ext = extensions.create("paperweight", PaperweightSourceGeneratorExt::class)
val applyAts by tasks.registering<ApplyAccessTransform> {
inputJar.set(rootProject.tasks.named<FixJarTask>("fixJar").flatMap { it.outputJar })
atFile.set(ext.atFile)
}
val copyResources by tasks.registering<CopyResources> {
inputJar.set(applyAts.flatMap { it.outputJar })
vanillaJar.set(rootProject.tasks.named<ExtractFromBundler>("extractFromBundler").flatMap { it.serverJar })
}
val libsFile = rootProject.layout.cache.resolve(SERVER_LIBRARIES_TXT)
val vanilla = configurations.register("vanillaServer") {
withDependencies {
dependencies {
val libs = libsFile.convertToPathOrNull()
if (libs != null && libs.exists()) {
libs.forEachLine { line ->
add(create(line))
}
}
}
}
}
dependencies {
vanilla.name(files(copyResources.flatMap { it.outputJar }))
}
afterEvaluate {
if (ext.addVanillaServerToImplementation.get()) {
configurations.named("implementation") {
extendsFrom(vanilla.get())
}
}
}
}
}

View file

@ -1,31 +0,0 @@
/*
* paperweight is a Gradle plugin for the PaperMC project.
*
* Copyright (c) 2023 Kyle Wood (DenWav)
* Contributors
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 only, no later versions.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.papermc.paperweight.extension
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import org.gradle.kotlin.dsl.property
abstract class PaperweightServerExtension(objects: ObjectFactory) {
val craftBukkitPackageVersion: Property<String> = objects.property()
}

View file

@ -1,36 +0,0 @@
/*
* paperweight is a Gradle plugin for the PaperMC project.
*
* Copyright (c) 2023 Kyle Wood (DenWav)
* Contributors
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 only, no later versions.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.papermc.paperweight.extension
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
@Suppress("LeakingThis")
abstract class PaperweightSourceGeneratorExt {
abstract val atFile: RegularFileProperty
abstract val addVanillaServerToImplementation: Property<Boolean>
init {
addVanillaServerToImplementation.convention(true)
}
}

View file

@ -1,161 +0,0 @@
/*
* paperweight is a Gradle plugin for the PaperMC project.
*
* Copyright (c) 2023 Kyle Wood (DenWav)
* Contributors
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 only, no later versions.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.papermc.paperweight.tasks
import io.papermc.paperweight.util.*
import java.nio.file.Files
import java.nio.file.Path
import java.util.stream.Collectors
import kotlin.io.path.*
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.work.ChangeType
import org.gradle.work.Incremental
import org.gradle.work.InputChanges
abstract class FilterPatchedFiles : BaseTask() {
@get:InputDirectory
@get:Incremental
abstract val inputSrcDir: DirectoryProperty
@get:InputDirectory
@get:Incremental
abstract val inputResourcesDir: DirectoryProperty
@get:InputFile
abstract val vanillaJar: RegularFileProperty
@get:OutputFile
abstract val outputJar: RegularFileProperty
override fun init() {
outputJar.convention(defaultOutput())
}
@TaskAction
fun run(changes: InputChanges) {
if (!changes.isIncremental) {
return runFull()
}
val srcAdded = changes.added(inputSrcDir)
val srcRemoved = changes.removed(inputSrcDir)
val resourceAdded = changes.added(inputResourcesDir)
val resourceRemoved = changes.removed(inputResourcesDir)
if (srcAdded.isEmpty() && srcRemoved.isEmpty() && resourceAdded.isEmpty() && resourceRemoved.isEmpty()) {
logger.info("No adds or removes, not doing work.")
didWork = false
return
}
vanillaJar.path.openZip().use { vanillaFs ->
val vanillaRoot = vanillaFs.rootDirectories.single()
outputJar.path.openZip().use { outputFs ->
val outputRoot = outputFs.rootDirectories.single()
for (add in resourceAdded) {
if (vanillaRoot.resolve(add).exists()) {
outputRoot.resolve(add).deleteIfExists()
}
}
for (del in resourceRemoved) {
val vanilla = vanillaRoot.resolve(del)
if (vanilla.exists()) {
val out = outputRoot.resolve(del)
out.parent.createDirectories()
out.deleteIfExists()
vanilla.copyTo(out)
}
}
for (add in srcAdded) {
val p = add.removeSuffix(".java") + ".class"
val vanilla = vanillaRoot.resolve(p)
if (vanilla.exists()) {
val outFile = outputRoot.resolve(p)
val outDir = outFile.parent
val paths = outDir.listDirectoryEntries("${vanilla.name.removeSuffix(".class")}$*.class").toMutableList()
paths.add(outFile)
paths.forEach { it.deleteIfExists() }
}
}
for (del in srcRemoved) {
val p = del.removeSuffix(".java") + ".class"
val vanillaFile = vanillaRoot.resolve(p)
if (vanillaFile.exists()) {
val paths = vanillaFile.parent.listDirectoryEntries("${vanillaFile.name.removeSuffix(".class")}$*.class").toMutableList()
paths.add(vanillaFile)
paths.forEach {
val out = outputRoot.resolve(it.relativeTo(vanillaRoot))
out.parent.createDirectories()
out.deleteIfExists()
it.copyTo(out)
}
}
}
}
}
}
private fun runFull() {
val srcFiles = collectFiles(inputSrcDir.path)
val resourceFiles = collectFiles(inputResourcesDir.path)
filterJar(
vanillaJar.path,
outputJar.path,
listOf()
) {
if (!it.isRegularFile()) {
false
} else if (it.nameCount > 1) {
val path = it.subpath(0, it.nameCount - 1).resolve(it.fileName.toString().split("$")[0].removeSuffix(".class")).toString()
!srcFiles.contains("$path.java") && !resourceFiles.contains(path)
} else {
true
}
}
}
private fun collectFiles(dir: Path): Set<String> {
return Files.walk(dir).use { stream ->
stream.filter { it.isRegularFile() }
.map { it.relativeTo(dir).invariantSeparatorsPathString }
.collect(Collectors.toUnmodifiableSet())
}
}
private fun InputChanges.added(baseDir: DirectoryProperty): Set<String> {
return getFileChanges(baseDir).filter { it.changeType == ChangeType.ADDED }
.map { it.file.toPath().relativeTo(baseDir.path).invariantSeparatorsPathString }
.toSet()
}
private fun InputChanges.removed(baseDir: DirectoryProperty): Set<String> {
return getFileChanges(baseDir).filter { it.changeType == ChangeType.REMOVED }
.map { it.file.toPath().relativeTo(baseDir.path).invariantSeparatorsPathString }
.toSet()
}
}

View file

@ -1,156 +0,0 @@
/*
* paperweight is a Gradle plugin for the PaperMC project.
*
* Copyright (c) 2023 Kyle Wood (DenWav)
* Contributors
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 only, no later versions.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.papermc.paperweight.tasks
import dev.denwav.hypo.asm.AsmClassDataProvider
import dev.denwav.hypo.core.HypoConfig
import dev.denwav.hypo.core.HypoContext
import dev.denwav.hypo.hydrate.HydrationManager
import dev.denwav.hypo.mappings.ChangeChain
import dev.denwav.hypo.mappings.ChangeRegistry
import dev.denwav.hypo.mappings.MappingsCompletionManager
import dev.denwav.hypo.mappings.contributors.ChangeContributor
import dev.denwav.hypo.model.ClassProviderRoot
import dev.denwav.hypo.model.data.ClassData
import io.papermc.paperweight.util.*
import io.papermc.paperweight.util.constants.*
import javax.inject.Inject
import kotlin.io.path.*
import org.cadixdev.lorenz.model.ClassMapping
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.*
import org.gradle.kotlin.dsl.*
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import org.gradle.workers.WorkerExecutor
@CacheableTask
abstract class GenerateRelocatedReobfMappings : JavaLauncherTask() {
@get:InputFile
@get:PathSensitive(PathSensitivity.NONE)
abstract val inputMappings: RegularFileProperty
@get:Classpath
abstract val inputJar: RegularFileProperty
@get:OutputFile
abstract val outputMappings: RegularFileProperty
@get:Internal
abstract val jvmArgs: ListProperty<String>
@get:Inject
abstract val workerExecutor: WorkerExecutor
@get:Input
abstract val craftBukkitPackageVersion: Property<String>
override fun init() {
super.init()
jvmArgs.convention(listOf("-Xmx2G"))
}
@TaskAction
fun run() {
val queue = workerExecutor.processIsolation {
forkOptions.jvmArgs(jvmArgs.get())
forkOptions.executable(launcher.get().executablePath.path.absolutePathString())
}
queue.submit(Action::class) {
inputMappings.set(this@GenerateRelocatedReobfMappings.inputMappings)
inputJar.set(this@GenerateRelocatedReobfMappings.inputJar)
craftBukkitPackageVersion.set(this@GenerateRelocatedReobfMappings.craftBukkitPackageVersion)
outputMappings.set(this@GenerateRelocatedReobfMappings.outputMappings)
}
}
abstract class Action : WorkAction<Action.Parameters> {
interface Parameters : WorkParameters {
val inputMappings: RegularFileProperty
val inputJar: RegularFileProperty
val craftBukkitPackageVersion: Property<String>
val outputMappings: RegularFileProperty
}
override fun execute() {
val mappingsIn = MappingFormats.TINY.read(
parameters.inputMappings.path,
DEOBF_NAMESPACE,
SPIGOT_NAMESPACE
)
val mappingsOut = HypoContext.builder()
.withConfig(HypoConfig.builder().setRequireFullClasspath(false).withParallelism(1).build())
.withProvider(AsmClassDataProvider.of(ClassProviderRoot.fromJar(parameters.inputJar.path)))
.withContextProvider(AsmClassDataProvider.of(ClassProviderRoot.ofJdk()))
.build().use { hypoContext ->
HydrationManager.createDefault().hydrate(hypoContext)
ChangeChain.create()
.addLink(CraftBukkitRelocation(parameters.craftBukkitPackageVersion.get()))
.applyChain(mappingsIn, MappingsCompletionManager.create(hypoContext))
}
MappingFormats.TINY.write(
mappingsOut,
parameters.outputMappings.path,
DEOBF_NAMESPACE,
SPIGOT_NAMESPACE
)
}
}
class CraftBukkitRelocation(packageVersion: String) : ChangeContributor {
companion object {
const val PREFIX = "org/bukkit/craftbukkit/"
const val MAIN = "${PREFIX}Main"
}
private val relocateTo: String = "$PREFIX$packageVersion"
override fun name(): String = "CraftBukkitRelocation"
override fun contribute(
currentClass: ClassData?,
classMapping: ClassMapping<*, *>?,
context: HypoContext,
registry: ChangeRegistry
) {
if (currentClass == null || classMapping != null) {
return
}
if (currentClass.name().startsWith(PREFIX) && !currentClass.name().startsWith(MAIN)) {
registry.submitChange(
GenerateReobfMappings.AddClassMappingChange(
currentClass.name(),
"$relocateTo/${currentClass.name().substring(PREFIX.length)}"
)
)
}
}
}
}

View file

@ -1,145 +0,0 @@
/*
* paperweight is a Gradle plugin for the PaperMC project.
*
* Copyright (c) 2023 Kyle Wood (DenWav)
* Contributors
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 only, no later versions.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.papermc.paperweight.tasks
import io.papermc.paperweight.util.*
import java.nio.file.Path
import kotlin.io.path.*
import org.gradle.api.Action
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.*
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.tree.ClassNode
@Suppress("LeakingThis")
abstract class RelocateClassNameConstants : BaseTask() {
@get:InputFile
abstract val inputJar: RegularFileProperty
@get:OutputFile
abstract val outputJar: RegularFileProperty
@get:Nested
@get:Optional
abstract val relocations: ListProperty<RelocationInput>
@get:Input
@get:Optional
abstract val processOnly: ListProperty<String>
fun relocate(fromPackage: String, toPackage: String, op: Action<RelocationInput>) {
relocations.add(
objects.newInstance<RelocationInput>().apply {
this.fromPackage.set(fromPackage)
this.toPackage.set(toPackage)
op.execute(this)
}
)
}
init {
outputJar.convention(defaultOutput())
processOnly.convention(
listOf(
"org/bukkit/craftbukkit/**/*.class",
"org/bukkit/craftbukkit/*.class"
)
)
}
@TaskAction
fun run() {
outputJar.path.deleteForcefully()
outputJar.path.parent.createDirectories()
val relocations = relocations.get().map {
RelocationWrapper(Relocation(null, it.fromPackage.get(), it.toPackage.get(), emptyList()))
}
outputJar.path.writeZip().use { outputFs ->
inputJar.path.openZip().use { inputFs ->
val includes = processOnly.getOrElse(emptyList()).map {
inputFs.getPathMatcher("glob:${if (it.startsWith('/')) it else "/$it"}")
}
JarProcessing.processJar(
inputFs,
outputFs,
object : JarProcessing.ClassProcessor.VisitorBased {
override fun shouldProcess(file: Path): Boolean =
includes.isEmpty() || includes.any { it.matches(file) }
override fun processClass(node: ClassNode, parent: ClassVisitor, classNodeCache: ClassNodeCache): ClassVisitor =
ConstantRelocatingClassVisitor(parent, relocations)
}
)
}
}
}
private class ConstantRelocatingClassVisitor(
parent: ClassVisitor,
private val relocations: List<RelocationWrapper>
) : ClassVisitor(Opcodes.ASM9, parent) {
override fun visitMethod(
access: Int,
name: String?,
descriptor: String?,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor {
return object : MethodVisitor(Opcodes.ASM9, super.visitMethod(access, name, descriptor, signature, exceptions)) {
override fun visitLdcInsn(value: Any?) {
if (value is String) {
var v: String = value
for (relocation in relocations) {
if (v.startsWith(relocation.fromDot)) {
v = v.replace(relocation.fromDot, relocation.toDot)
} else if (v.startsWith(relocation.fromSlash)) {
v = v.replace(relocation.fromSlash, relocation.toSlash)
}
}
super.visitLdcInsn(v)
} else {
super.visitLdcInsn(value)
}
}
}
}
}
abstract class RelocationInput {
@get:Input
abstract val fromPackage: Property<String>
@get:Input
abstract val toPackage: Property<String>
}
}

View file

@ -1,47 +0,0 @@
/*
* paperweight is a Gradle plugin for the PaperMC project.
*
* Copyright (c) 2023 Kyle Wood (DenWav)
* Contributors
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 only, no later versions.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.papermc.paperweight.userdev.internal
import org.gradle.api.artifacts.CacheableRule
import org.gradle.api.artifacts.ComponentMetadataContext
import org.gradle.api.artifacts.ComponentMetadataRule
/**
* Excludes `junit:junit` from the transitive dependencies of all variants.
*/
@CacheableRule
abstract class JunitExclusionRule : ComponentMetadataRule {
companion object {
const val TARGET = "com.googlecode.json-simple:json-simple"
}
override fun execute(ctx: ComponentMetadataContext) {
ctx.details.allVariants {
withDependencies {
removeIf {
it.group == "junit" && it.name == "junit"
}
}
}
}
}

View file

@ -4,7 +4,7 @@ plugins {
}
dependencies {
shade(projects.nuggetLib)
shade(projects.paperweightLib)
implementation(libs.bundles.kotson)
}

View file

@ -35,21 +35,16 @@ import io.papermc.paperweight.util.constants.*
import java.io.File
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.logging.Logging
import org.gradle.api.tasks.Delete
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.bundling.Zip
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.*
class PaperweightCore : Plugin<Project> {
companion object {
private val logger = Logging.getLogger(PaperweightCore::class.java)
}
override fun apply(target: Project) {
checkJavaVersion()
Git.checkForGit()
printId<PaperweightCore>("nugget-core", target.gradle)
printId<PaperweightCore>("paperweight-core", target.gradle)
val ext = target.extensions.create(PAPERWEIGHT_EXTENSION, PaperweightCoreExtension::class, target)
@ -63,14 +58,14 @@ class PaperweightCore : Plugin<Project> {
// Make sure the submodules are initialized, since there are files there
// which are required for configuration
target.layout.maybeInitSubmodules(target.offlineMode(), logger)
target.layout.initSubmodules()
target.configurations.create(PARAM_MAPPINGS_CONFIG)
target.configurations.create(REMAPPER_CONFIG)
target.configurations.create(DECOMPILER_CONFIG)
target.configurations.create(PAPERCLIP_CONFIG)
if (target.providers.gradleProperty("nugget.dev").orNull == "true") {
if (target.providers.gradleProperty("paperweight.dev").orNull == "true") {
target.tasks.register<CreateDiffOutput>("diff") {
inputDir.convention(ext.paper.paperServerDir.map { it.dir("src/main/java") })
val prop = target.providers.gradleProperty("paperweight.diff.output")
@ -143,24 +138,21 @@ class PaperweightCore : Plugin<Project> {
val cache = target.layout.cache
val serverProj = target.ext.serverProject.orNull ?: return@afterEvaluate
val serverJar = serverProj.tasks.register("serverJar", Zip::class)
serverProj.apply(plugin = "com.github.johnrengelman.shadow")
val shadowJar = serverProj.tasks.named("shadowJar", Jar::class)
tasks.generateReobfMappings {
inputJar.set(serverJar.flatMap { it.archiveFile })
}
tasks.generateRelocatedReobfMappings {
inputJar.set(serverJar.flatMap { it.archiveFile })
inputJar.set(shadowJar.flatMap { it.archiveFile })
}
val (includeMappings, reobfJar) = serverProj.setupServerProject(
val (_, reobfJar) = serverProj.setupServerProject(
target,
tasks.lineMapJar.flatMap { it.outputJar },
tasks.decompileJar.flatMap { it.outputJar },
ext.mcDevSourceDir.path,
cache.resolve(SERVER_LIBRARIES_TXT),
ext.paper.reobfPackagesToFix,
tasks.generateRelocatedReobfMappings,
serverJar
tasks.patchReobfMappings.flatMap { it.outputMappings }
) ?: return@afterEvaluate
devBundleTasks.configure(
@ -176,7 +168,7 @@ class PaperweightCore : Plugin<Project> {
tasks.extractFromBundler.map { it.versionJson.path }.convertToFileProvider(layout, providers)
) {
vanillaJarIncludes.set(ext.vanillaJarIncludes)
reobfMappingsFile.set(tasks.generateRelocatedReobfMappings.flatMap { it.outputMappings })
reobfMappingsFile.set(tasks.patchReobfMappings.flatMap { it.outputMappings })
paramMappingsCoordinates.set(
target.provider {
@ -191,7 +183,7 @@ class PaperweightCore : Plugin<Project> {
tasks.extractFromBundler.flatMap { it.versionJson },
tasks.extractFromBundler.flatMap { it.serverLibrariesList },
tasks.downloadServerJar.flatMap { it.outputJar },
includeMappings.flatMap { it.outputJar },
shadowJar,
reobfJar,
ext.minecraftVersion
)

View file

@ -57,9 +57,10 @@ open class AllTasks(
val copyResources by tasks.registering<CopyResources> {
inputJar.set(applyMergedAt.flatMap { it.outputJar })
vanillaJar.set(extractFromBundler.flatMap { it.serverJar })
includes.set(listOf("/data/**", "/assets/**", "version.json", "yggdrasil_session_pubkey.der", "pack.mcmeta", "flightrecorder-config.jfc"))
}
val decompileJar by tasks.registering<RunVineFlower> {
val decompileJar by tasks.registering<RunForgeFlower> {
executable.from(project.configurations.named(DECOMPILER_CONFIG))
inputJar.set(copyResources.flatMap { it.outputJar })
@ -175,9 +176,4 @@ open class AllTasks(
outputMappings.set(cache.resolve(PATCHED_REOBF_MOJANG_SPIGOT_MAPPINGS))
}
val generateRelocatedReobfMappings by tasks.registering<GenerateRelocatedReobfMappings> {
inputMappings.set(patchReobfMappings.flatMap { it.outputMappings })
outputMappings.set(cache.resolve(RELOCATED_PATCHED_REOBF_MOJANG_SPIGOT_MAPPINGS))
}
}

View file

@ -40,9 +40,7 @@ open class GeneralTasks(
) : InitialTasks(project) {
// Configuration won't necessarily always run, so do it as the first task when it's needed as well
val initSubmodules by tasks.registering<InitSubmodules> {
offlineMode.set(project.offlineMode())
}
val initSubmodules by tasks.registering<InitSubmodules>()
val buildDataInfo: Provider<BuildDataInfo> = project.contents(extension.craftBukkit.buildDataInfo) {
gson.fromJson(it)

View file

@ -2,10 +2,6 @@ plugins {
`config-kotlin`
}
repositories {
gradlePluginPortal()
}
dependencies {
implementation(libs.httpclient)
implementation(libs.bundles.kotson)

View file

@ -20,7 +20,29 @@
* USA
*/
package io.papermc.paperweight.util
package io.papermc.paperweight.extension
import org.gradle.api.model.ObjectFactory
import org.gradle.kotlin.dsl.*
abstract class RelocationExtension(objects: ObjectFactory) {
val relocations = objects.listProperty<Relocation>()
fun relocate(
owningLibraryCoordinates: String,
relocation: Pair<String, String>,
config: Relocation.() -> Unit = {}
) {
relocations.add(Relocation(owningLibraryCoordinates, relocation.first, relocation.second, arrayListOf()).apply(config))
}
fun relocate(
relocation: Pair<String, String>,
config: Relocation.() -> Unit = {}
) {
relocations.add(Relocation(null, relocation.first, relocation.second, arrayListOf()).apply(config))
}
}
data class Relocation(
val owningLibraryCoordinates: String?,

View file

@ -24,6 +24,8 @@ package io.papermc.paperweight.taskcontainers
import com.google.gson.JsonObject
import io.papermc.paperweight.tasks.*
import io.papermc.paperweight.tasks.packaging.CreateBundlerJar
import io.papermc.paperweight.tasks.packaging.CreatePaperclipJar
import io.papermc.paperweight.util.*
import io.papermc.paperweight.util.constants.*
import org.gradle.api.NamedDomainObjectContainer
@ -31,6 +33,7 @@ import org.gradle.api.Project
import org.gradle.api.file.RegularFile
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.bundling.AbstractArchiveTask
import org.gradle.kotlin.dsl.*
@Suppress("MemberVisibilityCanBePrivate")
@ -59,7 +62,7 @@ class BundlerJarTasks(
bundlerVersionJson: Provider<RegularFile>,
serverLibrariesList: Provider<RegularFile>,
vanillaJar: Provider<RegularFile>,
mojangJar: Provider<RegularFile>,
shadowJar: TaskProvider<out AbstractArchiveTask>,
reobfJar: TaskProvider<RemapJar>,
mcVersion: Provider<String>
) {
@ -67,7 +70,7 @@ class BundlerJarTasks(
bundlerVersionJson,
serverLibrariesList,
vanillaJar,
mojangJar,
shadowJar.flatMap { it.archiveFile },
)
createReobfBundlerJar.configureWith(
bundlerVersionJson,
@ -75,6 +78,19 @@ class BundlerJarTasks(
vanillaJar,
reobfJar.flatMap { it.outputJar },
)
createReobfBundlerJar {
remapLibraries.configureEach {
mappingsFile.set(reobfJar.flatMap { it.mappingsFile })
fromNamespace.set(reobfJar.flatMap { it.fromNamespace })
toNamespace.set(reobfJar.flatMap { it.toNamespace })
remapClasspath.from(reobfJar.map { it.remapClasspath })
// add mc to remap classpath
remapClasspath.from(reobfJar.flatMap { it.inputJar })
remapper.setFrom(reobfJar.map { it.remapper })
remapperArgs.set(reobfJar.flatMap { it.remapperArgs })
jvmArgs.set(reobfJar.flatMap { it.jvmArgs })
}
}
createPaperclipJar.configureWith(vanillaJar, createBundlerJar, mcVersion)
createReobfPaperclipJar.configureWith(vanillaJar, createReobfBundlerJar, mcVersion)

View file

@ -22,8 +22,11 @@
package io.papermc.paperweight.taskcontainers
import io.papermc.paperweight.extension.RelocationExtension
import io.papermc.paperweight.taskcontainers.BundlerJarTasks.Companion.registerVersionArtifact
import io.papermc.paperweight.tasks.*
import io.papermc.paperweight.tasks.packaging.CreateBundlerJar
import io.papermc.paperweight.tasks.packaging.CreatePaperclipJar
import io.papermc.paperweight.util.*
import io.papermc.paperweight.util.constants.*
import java.nio.file.Path
@ -82,7 +85,7 @@ class DevBundleTasks(
registerVersionArtifact(
bundlerJarName,
versionJsonFile,
serverProj.tasks.named<IncludeMappings>("includeMappings").flatMap { it.outputJar }
serverProj.tasks.named<FixJarForReobf>("fixJarForReobf").flatMap { it.inputJar }
)
}
}
@ -107,6 +110,7 @@ class DevBundleTasks(
serverProject.set(serverProj)
runtimeConfiguration.set(project.configurations.named(SERVER_RUNTIME_CLASSPATH))
relocations.set(serverProj.extensions.getByType<RelocationExtension>().relocations.map { gson.toJson(it) })
decompiledJar.pathProvider(decompileJar)
atFile.pathProvider(accessTransformFile)

View file

@ -49,16 +49,6 @@ abstract class CopyResources : BaseTask() {
override fun init() {
outputJar.convention(defaultOutput())
includes.convention(
listOf(
"/data/**",
"/assets/**",
"version.json",
"yggdrasil_session_pubkey.der",
"pack.mcmeta",
"flightrecorder-config.jfc",
)
)
}
@TaskAction

View file

@ -0,0 +1,94 @@
/*
* paperweight is a Gradle plugin for the PaperMC project.
*
* Copyright (c) 2023 Kyle Wood (DenWav)
* Contributors
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 only, no later versions.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.papermc.paperweight.tasks
import io.papermc.paperweight.util.*
import java.nio.file.Files
import java.nio.file.Path
import java.util.stream.Collectors
import kotlin.io.path.*
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
abstract class FilterProjectDir : BaseTask() {
@get:InputDirectory
abstract val inputSrcDir: DirectoryProperty
@get:InputDirectory
abstract val inputResourcesDir: DirectoryProperty
@get:InputFile
abstract val vanillaJar: RegularFileProperty
@get:OutputFile
abstract val outputJar: RegularFileProperty
override fun init() {
outputJar.convention(defaultOutput())
}
@TaskAction
fun run() {
val output = outputJar.path
val target = output.resolveSibling("${output.name}.dir")
target.createDirectories()
vanillaJar.path.openZip().use { zip ->
val srcFiles = collectFiles(inputSrcDir.path)
val resourceFiles = collectFiles(inputResourcesDir.path)
zip.walk().use { stream ->
stream
.filter { it.isRegularFile() }
.filter {
if (it.nameCount > 1) {
val path = it.subpath(0, it.nameCount - 1).resolve(it.fileName.toString().split("$")[0].removeSuffix(".class")).toString()
!srcFiles.contains("$path.java") && !resourceFiles.contains(path)
} else {
true
}
}.forEach { f ->
val targetFile = target.resolve(f.invariantSeparatorsPathString.substring(1))
targetFile.parent.createDirectories()
f.copyTo(targetFile)
}
}
}
zip(target, output)
target.deleteRecursive()
}
private fun collectFiles(dir: Path): Set<String> {
return Files.walk(dir).use { stream ->
stream.filter { it.isRegularFile() }
.map { it.relativeTo(dir).invariantSeparatorsPathString }
.collect(Collectors.toUnmodifiableSet())
}
}
}

View file

@ -23,6 +23,8 @@
package io.papermc.paperweight.tasks
import io.papermc.paperweight.PaperweightException
import io.papermc.paperweight.extension.Relocation
import io.papermc.paperweight.extension.RelocationWrapper
import io.papermc.paperweight.util.*
import io.papermc.paperweight.util.constants.*
import io.papermc.paperweight.util.data.*
@ -33,8 +35,10 @@ import java.nio.file.Path
import java.util.Locale
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
import java.util.stream.Collectors
import javax.inject.Inject
import kotlin.io.path.*
import org.apache.tools.ant.types.selectors.SelectorUtils
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
@ -79,6 +83,9 @@ abstract class GenerateDevBundle : DefaultTask() {
@get:Input
abstract val apiCoordinates: Property<String>
@get:Input
abstract val mojangApiCoordinates: Property<String>
@get:Input
abstract val vanillaJarIncludes: ListProperty<String>
@ -94,6 +101,9 @@ abstract class GenerateDevBundle : DefaultTask() {
@get:Classpath
abstract val runtimeConfiguration: Property<Configuration>
@get:Input
abstract val relocations: Property<String>
@get:Input
abstract val paramMappingsUrl: Property<String>
@ -170,6 +180,8 @@ abstract class GenerateDevBundle : DefaultTask() {
workingDir.createDirectories()
sourceDir.path.copyRecursivelyTo(workingDir)
relocate(relocations(), workingDir)
Files.walk(workingDir).use { stream ->
decompiledJar.path.openZip().use { decompJar ->
val decompRoot = decompJar.rootDirectories.single()
@ -202,6 +214,60 @@ abstract class GenerateDevBundle : DefaultTask() {
workingDir.deleteRecursive()
}
private fun relocate(relocations: List<Relocation>, workingDir: Path) {
val wrappedRelocations = relocations.map { RelocationWrapper(it) }
Files.walk(workingDir).use { stream ->
stream.filter { it.isRegularFile() && it.name.endsWith(".java") }
.forEach { path -> replaceRelocationsInFile(path, wrappedRelocations) }
}
relocateFiles(wrappedRelocations, workingDir)
}
private fun replaceRelocationsInFile(path: Path, relocations: List<RelocationWrapper>) {
var content = path.readText(Charsets.UTF_8)
// Use hashes as intermediary to avoid double relocating
for (relocation in relocations) {
content = content.replace(relocation.fromDot, '.' + relocation.hashCode().toString())
.replace(relocation.fromSlash, '/' + relocation.hashCode().toString())
}
for (relocation in relocations) {
content = content.replace('.' + relocation.hashCode().toString(), relocation.toDot)
.replace('/' + relocation.hashCode().toString(), relocation.toSlash)
}
path.writeText(content, Charsets.UTF_8)
}
private fun relocateFiles(relocations: List<RelocationWrapper>, workingDir: Path) {
Files.walk(workingDir).use { stream -> stream.collect(Collectors.toList()) }
.asSequence().filter { it.isRegularFile() && it.name.endsWith(".java") }
.forEach { path ->
val potential = path.relativeTo(workingDir).invariantSeparatorsPathString
for (relocation in relocations) {
if (potential.startsWith(relocation.fromSlash)) {
if (excluded(relocation.relocation, potential)) {
break
}
val dest = workingDir.resolve(potential.replace(relocation.fromSlash, relocation.toSlash))
dest.parent.createDirectories()
path.moveTo(dest)
break
}
}
}
}
private fun excluded(relocation: Relocation, potential: String): Boolean = relocation.excludes.map {
it.replace('.', '/')
}.any { exclude ->
SelectorUtils.matchPath(exclude, potential, true)
}
private fun diffFiles(fileName: String, original: Path, patched: Path): String {
val dir = createTempDirectory("diff")
try {
@ -254,7 +320,7 @@ abstract class GenerateDevBundle : DefaultTask() {
}
private fun asString(out: ByteArrayOutputStream) = String(out.toByteArray(), Charset.defaultCharset())
.replace(System.lineSeparator(), "\n")
.replace(System.getProperty("line.separator"), "\n")
@Suppress("SameParameterValue")
private fun createBundleConfig(dataTargetDir: String, patchTargetDir: String): DevBundleConfig {
@ -262,6 +328,7 @@ abstract class GenerateDevBundle : DefaultTask() {
minecraftVersion = minecraftVersion.get(),
mappedServerCoordinates = serverCoordinates.get(),
apiCoordinates = "${apiCoordinates.get()}:${serverVersion.get()}",
mojangApiCoordinates = "${mojangApiCoordinates.get()}:${serverVersion.get()}",
buildData = createBuildDataConfig(dataTargetDir),
decompile = createDecompileRunner(),
remapper = createRemapDep(),
@ -269,6 +336,8 @@ abstract class GenerateDevBundle : DefaultTask() {
)
}
private fun relocations(): List<Relocation> = gson.fromJson(relocations.get())
private fun createBuildDataConfig(targetDir: String): BuildData {
return BuildData(
paramMappings = MavenDep(paramMappingsUrl.get(), listOf(paramMappingsCoordinates.get())),
@ -279,7 +348,7 @@ abstract class GenerateDevBundle : DefaultTask() {
compileDependencies = determineLibraries(vanillaServerLibraries.get()).sorted(),
runtimeDependencies = collectRuntimeDependencies().map { it.coordinates }.sorted(),
libraryRepositories = libraryRepositories.get(),
relocations = emptyList(), // Nothing is relocated in the dev bundle as of 1.20.5
relocations = relocations(),
minecraftRemapArgs = TinyRemapper.minecraftRemapArgs,
pluginRemapArgs = TinyRemapper.pluginRemapArgs,
)
@ -312,7 +381,13 @@ abstract class GenerateDevBundle : DefaultTask() {
}
}
return new.map { it.toString() }.toSet()
val result = new.map { it.toString() }.toMutableSet()
// Remove relocated libraries
val libs = relocations().mapNotNull { it.owningLibraryCoordinates }
result.removeIf { coords -> libs.any { coords.startsWith(it) } }
return result
}
private val ResolvedArtifactResult.coordinates: String
@ -326,7 +401,7 @@ abstract class GenerateDevBundle : DefaultTask() {
private fun createDecompileRunner(): Runner {
return Runner(
dep = determineMavenDep(decompilerUrl, decompilerConfig),
args = vineFlowerArgList
args = forgeFlowerArgList
)
}
@ -337,7 +412,7 @@ abstract class GenerateDevBundle : DefaultTask() {
val minecraftVersion: String,
val mappedServerCoordinates: String,
val apiCoordinates: String,
val mojangApiCoordinates: String? = null,
val mojangApiCoordinates: String,
val buildData: BuildData,
val decompile: Runner,
val remapper: MavenDep,
@ -368,7 +443,7 @@ abstract class GenerateDevBundle : DefaultTask() {
const val mojangMappedPaperclipFileName = "paperclip-$DEOBF_NAMESPACE.jar"
// Should be bumped when the dev bundle config/contents changes in a way which will require users to update paperweight
const val currentDataVersion = 5
const val currentDataVersion = 3
fun createCoordinatesFor(project: Project): String =
sequenceOf(project.group, project.name.lowercase(Locale.ENGLISH), "userdev-" + project.version).joinToString(":")

View file

@ -74,7 +74,7 @@ abstract class GenerateReobfMappings : JavaLauncherTask() {
abstract val reobfMappings: RegularFileProperty
@get:Internal
abstract val jvmArgs: ListProperty<String>
abstract val jvmargs: ListProperty<String>
@get:Inject
abstract val workerExecutor: WorkerExecutor
@ -86,13 +86,13 @@ abstract class GenerateReobfMappings : JavaLauncherTask() {
override fun init() {
super.init()
jvmArgs.convention(listOf("-Xmx2G"))
jvmargs.convention(listOf("-Xmx2G"))
}
@TaskAction
fun run() {
val queue = workerExecutor.processIsolation {
forkOptions.jvmArgs(jvmArgs.get())
forkOptions.jvmArgs(jvmargs.get())
forkOptions.executable(launcher.get().executablePath.path.absolutePathString())
}

View file

@ -22,8 +22,11 @@
package io.papermc.paperweight.tasks
import io.papermc.paperweight.util.*
import kotlin.io.path.*
import io.papermc.paperweight.util.defaultOutput
import io.papermc.paperweight.util.openZip
import io.papermc.paperweight.util.path
import kotlin.io.path.copyTo
import kotlin.io.path.createDirectories
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
@ -57,10 +60,6 @@ abstract class IncludeMappings : BaseTask() {
val dest = fs.getPath(mappingsDest.get())
dest.parent.createDirectories()
mappings.path.copyTo(dest)
fs.modifyManifest {
mainAttributes.putValue("Included-Mappings-Hash", mappings.path.hashFile(HashingAlgorithm.SHA256).asHexString().uppercase())
}
}
}
}

View file

@ -26,27 +26,17 @@ import io.papermc.paperweight.util.*
import javax.inject.Inject
import org.gradle.api.DefaultTask
import org.gradle.api.file.ProjectLayout
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.UntrackedTask
@Suppress("LeakingThis")
@UntrackedTask(because = "Git tracks the state")
abstract class InitSubmodules : DefaultTask() {
@get:Inject
abstract val layout: ProjectLayout
@get:Input
abstract val offlineMode: Property<Boolean>
init {
offlineMode.convention(false)
}
@TaskAction
fun run() {
layout.maybeInitSubmodules(offlineMode.get(), logger)
layout.initSubmodules()
}
}

View file

@ -97,7 +97,7 @@ abstract class RebuildGitPatches : ControllableOutputTask() {
git("fetch", "--all", "--prune").runSilently(silenceErr = true)
git(
"format-patch",
"--diff-algorithm=myers", "--zero-commit", "--full-index", "--no-signature", "--no-stat", "-N",
"--zero-commit", "--full-index", "--no-signature", "--no-stat", "-N",
"-o", patchFolder.absolutePathString(),
baseRef.get()
).executeSilently()
@ -131,7 +131,7 @@ abstract class RebuildGitPatches : ControllableOutputTask() {
try {
for (patch in patchFiles) {
futures += executor.submit {
val hasNoChanges = git("diff", "--diff-algorithm=myers", "--staged", patch.name).getText().lineSequence()
val hasNoChanges = git("diff", "--staged", patch.name).getText().lineSequence()
.filter { it.startsWith('+') || it.startsWith('-') }
.filterNot { it.startsWith("+++") || it.startsWith("---") }
.all { it.startsWith("+index") || it.startsWith("-index") }

View file

@ -36,36 +36,13 @@ import org.gradle.api.tasks.*
import org.gradle.jvm.toolchain.JavaLauncher
@CacheableTask
abstract class RemapJar : JavaLauncherTask() {
abstract class RemapJar : JavaLauncherTask(), RemapJarParams {
@get:Classpath
abstract val inputJar: RegularFileProperty
@get:InputFile
@get:PathSensitive(PathSensitivity.NONE)
abstract val mappingsFile: RegularFileProperty
@get:Input
abstract val fromNamespace: Property<String>
@get:Input
abstract val toNamespace: Property<String>
@get:CompileClasspath
abstract val remapClasspath: ConfigurableFileCollection
@get:Classpath
abstract val remapper: ConfigurableFileCollection
@get:Input
abstract val remapperArgs: ListProperty<String>
@get:OutputFile
abstract val outputJar: RegularFileProperty
@get:Internal
abstract val jvmArgs: ListProperty<String>
override fun init() {
super.init()
@ -76,43 +53,41 @@ abstract class RemapJar : JavaLauncherTask() {
@TaskAction
fun run() {
if (inputJar.path.absolute().normalize() == outputJar.path.absolute().normalize()) {
throw PaperweightException(
"Invalid configuration, inputJar and outputJar point to the same path: ${inputJar.path}\n" +
"Consider removing customization of output locations, following the default Gradle conventions."
)
}
if (toNamespace.get() != fromNamespace.get()) {
val logFile = layout.cache.resolve(paperTaskOutput("log"))
TinyRemapper.run(
argsList = remapperArgs.get(),
logFile = logFile,
inputJar = inputJar.path,
mappingsFile = mappingsFile.path,
fromNamespace = fromNamespace.get(),
toNamespace = toNamespace.get(),
remapClasspath = remapClasspath.files.map { it.toPath() },
remapper = remapper,
outputJar = outputJar.path,
launcher = launcher.get(),
workingDir = layout.cache,
jvmArgs = jvmArgs.get()
)
} else {
outputJar.path.deleteForcefully()
outputJar.path.parent.createDirectories()
inputJar.path.copyTo(outputJar.path)
}
outputJar.path.openZip().use { fs ->
fs.modifyManifest {
mainAttributes.putValue(MAPPINGS_NAMESPACE_MANIFEST_KEY, toNamespace.get())
}
}
TinyRemapper.run(
inputJar.path,
outputJar.path,
this,
launcher.get(),
layout.cache.resolve(paperTaskOutput("log")),
layout.cache
)
}
}
interface RemapJarParams {
@get:InputFile
@get:PathSensitive(PathSensitivity.NONE)
val mappingsFile: RegularFileProperty
@get:Input
val fromNamespace: Property<String>
@get:Input
val toNamespace: Property<String>
@get:CompileClasspath
val remapClasspath: ConfigurableFileCollection
@get:Classpath
val remapper: ConfigurableFileCollection
@get:Input
val remapperArgs: ListProperty<String>
@get:Internal
val jvmArgs: ListProperty<String>
}
object TinyRemapper {
private const val minecraftLvPattern = "\\$\\$\\d+"
private const val fixPackageAccessArg = "--fixpackageaccess"
@ -196,6 +171,30 @@ object TinyRemapper {
return args
}
fun run(
inputJar: Path,
outputJar: Path,
params: RemapJarParams,
launcher: JavaLauncher,
logFile: Path,
workingDir: Path,
) {
run(
argsList = params.remapperArgs.get(),
logFile = logFile,
inputJar = inputJar,
mappingsFile = params.mappingsFile.path,
fromNamespace = params.fromNamespace.get(),
toNamespace = params.toNamespace.get(),
remapClasspath = params.remapClasspath.files.map { it.toPath() },
remapper = params.remapper,
outputJar = outputJar,
launcher = launcher,
workingDir = workingDir,
jvmArgs = params.jvmArgs.get()
)
}
fun run(
argsList: List<String>,
logFile: Path,

View file

@ -45,7 +45,6 @@ import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.*
import org.gradle.kotlin.dsl.*
import org.gradle.workers.WorkAction
@ -102,9 +101,6 @@ abstract class RemapSources : JavaLauncherTask() {
@get:OutputFile
abstract val spigotRecompiledClasses: RegularFileProperty
@get:Input
abstract val sourceCompatibility: Property<Int>
override fun init() {
super.init()
@ -113,7 +109,6 @@ abstract class RemapSources : JavaLauncherTask() {
testsOutputZip.convention(defaultOutput("$name-tests", "jar"))
generatedAt.convention(defaultOutput("at"))
spigotRecompiledClasses.convention(defaultOutput("spigotRecompiledClasses", "txt"))
sourceCompatibility.convention(21)
}
@TaskAction
@ -145,8 +140,6 @@ abstract class RemapSources : JavaLauncherTask() {
outputDir.set(srcOut)
generatedAtOutput.set(generatedAt.path)
sourceCompat.set(sourceCompatibility.orNull)
}
val testSrc = spigotServerDir.path.resolve("src/test/java")
@ -167,8 +160,6 @@ abstract class RemapSources : JavaLauncherTask() {
cacheDir.set(this@RemapSources.layout.cache)
outputDir.set(testOut)
sourceCompat.set(sourceCompatibility.orNull)
}
queue.await()
@ -219,7 +210,7 @@ abstract class RemapSources : JavaLauncherTask() {
// Remap any references Spigot maps to mojmap+yarn
Mercury().let { merc ->
merc.sourceCompatibility = parameters.sourceCompat.map { it.toString() }.orNull ?: JavaCore.VERSION_17
merc.sourceCompatibility = JavaCore.VERSION_17
merc.isGracefulClasspathChecks = true
merc.classPath.addAll(parameters.classpath.map { it.toPath() })
@ -274,8 +265,6 @@ abstract class RemapSources : JavaLauncherTask() {
val cacheDir: RegularFileProperty
val generatedAtOutput: RegularFileProperty
val outputDir: RegularFileProperty
val sourceCompat: Property<Int>
}
object ExplicitThisAdder : SourceRewriter {

View file

@ -25,8 +25,6 @@ package io.papermc.paperweight.tasks
import io.papermc.paperweight.util.*
import io.papermc.paperweight.util.constants.*
import java.nio.file.Path
import java.util.jar.Attributes
import java.util.jar.Manifest
import kotlin.io.path.*
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
@ -35,30 +33,29 @@ import org.gradle.api.provider.ListProperty
import org.gradle.api.tasks.*
import org.gradle.jvm.toolchain.JavaLauncher
val vineFlowerArgList: List<String> = listOf(
"--synthetic-not-set=true",
"--ternary-constant-simplification=true",
"--include-runtime=current",
"--decompile-complex-constant-dynamic=true",
"--indent-string= ",
"--decompile-inner=true", // is default
"--remove-bridge=true", // is default
"--decompile-generics=true", // is default
"--ascii-strings=false", // is default
"--remove-synthetic=true", // is default
"--include-classpath=true",
"--inline-simple-lambdas=true", // is default
"--ignore-invalid-bytecode=false", // is default
"--bytecode-source-mapping=true",
"--dump-code-lines=true",
"--override-annotation=false", // We add override annotations ourselves. Vineflower's impl doesn't work as well yet and conflicts
"-cfg", // Pass the libraries as an argument file to avoid command line length limits
val forgeFlowerArgList: List<String> = listOf(
"-ind= ",
"-din=1",
"-rbr=1",
"-dgs=1",
"-asc=1",
"-rsy=1",
"-iec=1",
"-jvn=0",
"-isl=0",
"-iib=1",
"-bsm=1",
"-dcl=1",
"-ovr=0", // We add override annotations ourselves. Vineflower's impl doesn't work as well yet and conflicts
"-pll=999999", // High line length to effectively disable formatter (only does anything on Vineflower)
"-log=TRACE",
"-cfg",
"{libraries}",
"{input}",
"{output}"
)
private fun List<String>.createDecompilerArgs(
private fun List<String>.createForgeFlowerArgs(
libraries: String,
input: String,
output: String,
@ -71,7 +68,7 @@ private fun List<String>.createDecompilerArgs(
}
}
fun runDecompiler(
fun runForgeFlower(
argsList: List<String>,
logFile: Path,
workingDir: Path,
@ -87,20 +84,15 @@ fun runDecompiler(
val tempFile = createTempFile("paperweight", "txt")
try {
val vineflower = isVineflower(executable)
tempFile.bufferedWriter().use { writer ->
for (lib in libs) {
if (lib.isLibraryJar) {
if (vineflower) {
writer.appendLine("--add-external=${lib.absolutePathString()}")
} else {
writer.appendLine("-e=${lib.absolutePathString()}")
}
writer.appendLine("-e=${lib.absolutePathString()}")
}
}
}
val argList = argsList.createDecompilerArgs(
val argList = argsList.createForgeFlowerArgs(
tempFile.absolutePathString(),
inputJar.absolutePathString(),
outputJar.absolutePathString(),
@ -116,19 +108,8 @@ fun runDecompiler(
}
}
private fun isVineflower(executable: FileCollection) = executable.files.any {
it.toPath().openZip().use { fs ->
val manifest = fs.getPath("META-INF/MANIFEST.MF").takeIf { f -> f.isRegularFile() }?.inputStream()?.buffered()?.use { reader ->
Manifest(reader)
}
manifest != null &&
manifest.mainAttributes.containsKey(Attributes.Name("Implementation-Name")) &&
manifest.mainAttributes.getValue("Implementation-Name").equals("Vineflower", ignoreCase = true)
}
}
@CacheableTask
abstract class RunVineFlower : JavaLauncherTask() {
abstract class RunForgeFlower : JavaLauncherTask() {
@get:Classpath
abstract val executable: ConfigurableFileCollection
@ -154,8 +135,8 @@ abstract class RunVineFlower : JavaLauncherTask() {
@TaskAction
fun run() {
runDecompiler(
vineFlowerArgList,
runForgeFlower(
forgeFlowerArgList,
layout.cache.resolve(paperTaskOutput("log")),
layout.cache,
executable,

View file

@ -68,7 +68,7 @@ abstract class ScanJar : JavaLauncherTask() {
override fun init() {
super.init()
jvmArgs.convention(listOf("-Xmx768m"))
jvmArgs.convention(listOf("-Xmx512m"))
log.set(layout.cache.resolve(paperTaskOutput("txt")))
}

View file

@ -31,19 +31,13 @@ import javax.inject.Inject
import javax.xml.parsers.DocumentBuilderFactory
import kotlin.io.path.*
import org.gradle.api.DefaultTask
import org.gradle.api.artifacts.component.ComponentIdentifier
import org.gradle.api.artifacts.dsl.DependencyFactory
import org.gradle.api.attributes.java.TargetJvmEnvironment
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.internal.project.ProjectInternal.DetachedResolver
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.*
import org.gradle.kotlin.dsl.*
import org.gradle.work.DisableCachingByDefault
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import org.gradle.workers.WorkQueue
@ -146,7 +140,7 @@ fun downloadMinecraftLibraries(
return queue
}
@DisableCachingByDefault(because = "Gradle handles caching")
@CacheableTask
abstract class DownloadSpigotDependencies : BaseTask() {
@get:InputFile
@ -173,11 +167,6 @@ abstract class DownloadSpigotDependencies : BaseTask() {
@get:Inject
abstract val workerExecutor: WorkerExecutor
@get:Inject
abstract val dependencyFactory: DependencyFactory
private val detachedResolver: DetachedResolver = (project as ProjectInternal).newDetachedResolver()
@TaskAction
fun run() {
val apiSetup = parsePom(apiPom.path)
@ -185,10 +174,12 @@ abstract class DownloadSpigotDependencies : BaseTask() {
val mcLibraries = mcLibrariesFile.path.readLines()
val out = outputDir.path
out.deleteRecursive()
val excludes = listOf(out.fileSystem.getPathMatcher("glob:*.etag"))
out.deleteRecursive(excludes)
val outSources = outputSourcesDir.path
outSources.deleteRecursive()
val excludesSources = listOf(outSources.fileSystem.getPathMatcher("glob:*.etag"))
outSources.deleteRecursive(excludesSources)
val spigotRepos = mutableSetOf<String>()
spigotRepos += apiSetup.repos
@ -198,74 +189,23 @@ abstract class DownloadSpigotDependencies : BaseTask() {
artifacts += apiSetup.artifacts
artifacts += serverSetup.artifacts
val resolver = detachedResolver
for (repo in spigotRepos) {
resolver.repositories.maven(repo)
}
val config = resolver.configurations.create("spigotDependencies") {
attributes {
attribute(TargetJvmEnvironment.TARGET_JVM_ENVIRONMENT_ATTRIBUTE, objects.named(TargetJvmEnvironment.STANDARD_JVM))
val queue = workerExecutor.noIsolation()
for (art in artifacts) {
queue.submit(DownloadWorker::class) {
repos.set(spigotRepos)
artifact.set(art.toString())
target.set(out)
downloadToDir.set(true)
downloader.set(this@DownloadSpigotDependencies.downloader)
}
}
for (artifact in artifacts) {
val gav = artifact.gav.let {
if (it == "com.google.guava:guava:32.1.2-jre") {
// https://github.com/google/guava/issues/6657
"com.google.guava:guava:32.1.3-jre"
} else {
it
if (!mcLibraries.contains(art.toString())) {
queue.submit(DownloadSourcesToDirAction::class) {
repos.set(spigotRepos)
artifact.set(art.toString())
target.set(outSources)
downloader.set(this@DownloadSpigotDependencies.downloader)
}
}
config.dependencies.add(
dependencyFactory.create(gav).also {
it.artifact {
artifact.classifier?.let { s -> classifier = s }
artifact.extension?.let { s -> extension = s }
}
}
)
}
// The source variants don't have transitives
val flatComponents = mutableSetOf<ComponentIdentifier>()
for (artifact in config.incoming.artifacts.artifacts) {
artifact.file.toPath().copyTo(outputDir.path.resolve(artifact.file.name).also { it.parent.createDirectories() }, true)
flatComponents += artifact.id.componentIdentifier
}
val sourcesConfig = resolver.configurations.create("spigotDependenciesSources") {
attributes {
// Mojang libs & Guava don't resolve metadata correctly, so we set the classifier below instead...
// attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME))
// attribute(DocsType.DOCS_TYPE_ATTRIBUTE, objects.named(DocsType.SOURCES))
// attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.EXTERNAL))
// attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category.DOCUMENTATION))
// Needed since we set the classifier instead of using above attributes
attribute(TargetJvmEnvironment.TARGET_JVM_ENVIRONMENT_ATTRIBUTE, objects.named(TargetJvmEnvironment.STANDARD_JVM))
}
}
for (component in flatComponents) {
sourcesConfig.dependencies.add(
dependencyFactory.create(component.displayName).also {
it.artifact {
classifier = "sources"
}
}
)
}
val sourcesView = sourcesConfig.incoming.artifactView {
componentFilter {
mcLibraries.none { l -> l == it.displayName } &&
// This is only needed since we don't use variant-aware resolution properly
it.displayName != "com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava"
}
}
for (artifact in sourcesView.artifacts.artifacts) {
artifact.file.toPath().copyTo(outputSourcesDir.path.resolve(artifact.file.name).also { it.parent.createDirectories() }, true)
}
}

View file

@ -20,13 +20,16 @@
* USA
*/
package io.papermc.paperweight.tasks
package io.papermc.paperweight.tasks.packaging
import io.papermc.paperweight.PaperweightException
import io.papermc.paperweight.tasks.*
import io.papermc.paperweight.util.*
import io.papermc.paperweight.util.constants.*
import io.papermc.paperweight.util.data.*
import java.nio.file.Path
import kotlin.io.path.*
import org.gradle.api.Named
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.component.ModuleComponentIdentifier
@ -39,7 +42,7 @@ import org.gradle.api.tasks.*
import org.gradle.kotlin.dsl.*
@CacheableTask
abstract class CreateBundlerJar : ZippedTask() {
abstract class CreateBundlerJar : JavaLauncherZippedTask() {
interface VersionArtifact {
@get:Input
@ -75,6 +78,14 @@ abstract class CreateBundlerJar : ZippedTask() {
@get:OutputFile
abstract val libraryChangesJson: RegularFileProperty
interface LibraryRemap : RemapJarParams, Named {
@Input
override fun getName(): String
}
@get:Nested
abstract val remapLibraries: NamedDomainObjectContainer<LibraryRemap>
private fun createVersionArtifactContainer(): NamedDomainObjectContainer<VersionArtifact> =
objects.domainObjectContainer(VersionArtifact::class) { objects.newInstance(it) }
@ -122,6 +133,8 @@ abstract class CreateBundlerJar : ZippedTask() {
val outputDir = rootDir.resolve("META-INF/libraries")
val workingDir = createTempDirectory("paperweight-bundler-remap")
val dependencies = collectDependencies()
for (dep in dependencies) {
val serverLibrary = serverLibraryEntries.firstOrNull {
@ -129,29 +142,65 @@ abstract class CreateBundlerJar : ZippedTask() {
it.id.name == dep.module.name &&
it.id.classifier == dep.module.classifier
}
val remapInfo = remapLibraries.findByName(dep.module.group + ':' + dep.module.name)
if (serverLibrary != null) {
if (serverLibrary.id.version == dep.module.version) {
// nothing to do
if (serverLibrary.id.version == dep.module.version && remapInfo == null) {
// nothing to do (no remap or version change)
libraries += serverLibrary
dep.copyTo(outputDir.resolve(dep.module.toPath()))
} else {
// we have a different version of this library
val newId = dep.module
val newPath = newId.toPath()
changedLibraries += LibraryChange(serverLibrary.id, serverLibrary.path, newId, newPath)
if (remapInfo != null) {
// we are remapping this library, may or may not be a different version
val newId = dep.module.copy(version = dep.module.version + "-remapped")
val newPath = newId.toPath()
changedLibraries += LibraryChange(serverLibrary.id, serverLibrary.path, newId, newPath)
val jarFile = dep.copyTo(outputDir.resolve(newPath))
TinyRemapper.run(
dep.file.toPath(),
outputDir.resolve(newPath),
remapInfo,
launcher.get(),
layout.cache.resolve(paperTaskOutput("remap${remapInfo.name.capitalized()}.log")),
workingDir
)
libraries += FileEntry(jarFile.sha256asHex(), newId, newPath)
libraries += FileEntry(outputDir.resolve(newPath).sha256asHex(), newId, newPath)
} else {
// we have a different version of this library (not remapped)
val newId = dep.module
val newPath = newId.toPath()
changedLibraries += LibraryChange(serverLibrary.id, serverLibrary.path, newId, newPath)
val jarFile = dep.copyTo(outputDir.resolve(newPath))
libraries += FileEntry(jarFile.sha256asHex(), newId, newPath)
}
}
} else {
// New dependency
val id = dep.module
val path = id.toPath()
val jarFile = dep.copyTo(outputDir.resolve(path))
if (remapInfo != null) {
// New dependency, remapped
val id = dep.module.copy(version = dep.module.version + "-remapped")
val path = id.toPath()
libraries += FileEntry(jarFile.sha256asHex(), id, path)
TinyRemapper.run(
dep.file.toPath(),
outputDir.resolve(path),
remapInfo,
launcher.get(),
layout.cache.resolve(paperTaskOutput("remap${remapInfo.name.capitalized()}.log")),
workingDir
)
libraries += FileEntry(outputDir.resolve(path).sha256asHex(), id, path)
} else {
// New dependency, not remapped
val id = dep.module
val path = id.toPath()
val jarFile = dep.copyTo(outputDir.resolve(path))
libraries += FileEntry(jarFile.sha256asHex(), id, path)
}
}
}
@ -200,10 +249,11 @@ abstract class CreateBundlerJar : ZippedTask() {
return when (val ident = id.componentIdentifier) {
is ModuleComponentIdentifier -> ModuleId.fromIdentifier(id)
is ProjectComponentIdentifier -> {
val capability = variant.capabilities.first()
val capability = variant.capabilities.single()
val version = capability.version ?: throw PaperweightException("Unknown version for ${capability.group}:${capability.name}")
ModuleId(capability.group, capability.name, version)
}
else -> throw PaperweightException("Unknown artifact result type: ${ident::class.java.name}")
}
}

View file

@ -20,9 +20,10 @@
* USA
*/
package io.papermc.paperweight.tasks
package io.papermc.paperweight.tasks.packaging
import io.papermc.paperweight.PaperweightException
import io.papermc.paperweight.tasks.*
import io.papermc.paperweight.util.*
import io.papermc.paperweight.util.data.*
import io.sigpipe.jbsdiff.Diff

View file

@ -103,7 +103,7 @@ class PatchApplier(
target.createDirectories()
git("checkout", remappedBranch).executeSilently()
git(
"format-patch", "--diff-algorith=myers", "--zero-commit", "--full-index", "--no-signature", "--no-stat", "-N", "-o",
"format-patch", "--zero-commit", "--full-index", "--no-signature", "--no-stat", "-N", "-o",
target.absolutePathString(), remappedBaseTag
).executeOut()
}
@ -114,7 +114,7 @@ class PatchApplier(
}
git("update-index", "--refresh").executeSilently()
if (git("diff-index", "--diff-algorithm=myers", "--quiet", "HEAD", "--").runSilently() == 0) {
if (git("diff-index", "--quiet", "HEAD", "--").runSilently() == 0) {
return git("log", unmappedBranch, "-1", "--pretty=%B").getText().trim() !=
git("log", remappedBranch, "-1", "--pretty=%B").getText().trim()
}

View file

@ -45,8 +45,7 @@ object McDev {
val (javaPatchLines, dataPatchLines) = readPatchLines(patches)
decompJar.openZip().use { zipFile ->
val decompSourceFiles = mutableSetOf<String>()
val decompDataFiles = mutableSetOf<String>()
val decompFiles = mutableSetOf<String>()
zipFile.walk().use { stream ->
for (zipEntry in stream) {
@ -54,10 +53,7 @@ object McDev {
val path = zipEntry.invariantSeparatorsPathString.substring(1)
if (path.endsWith(".java")) {
decompSourceFiles += path
}
if (path.startsWith("data/")) {
decompDataFiles += path
decompFiles += path
}
// pull in all package-info classes
@ -74,14 +70,9 @@ object McDev {
}
}
val exactJavaImports = javaPatchLines.filter { decompSourceFiles.contains(it) }
val exactJavaImports = javaPatchLines.filter { decompFiles.contains(it) }
.map { targetDir.resolve(it) }
val exactDataImports = if (dataTargetDir != null) {
dataPatchLines.map { "data/minecraft/$it" }.filter { decompDataFiles.contains(it) }
.map { dataTargetDir.resolve(it) }
} else {
listOf()
}
val exactDataImports = if (dataTargetDir != null) dataPatchLines.map { dataTargetDir.resolve("data/minecraft/$it") } else listOf()
val (additionalSrcImports, additionalDataImports) = readAdditionalImports(importsFile)

View file

@ -41,7 +41,6 @@ const val MAVEN_CENTRAL_URL = "https://repo.maven.apache.org/maven2/"
const val PARAM_MAPPINGS_CONFIG = "paramMappings"
const val REMAPPER_CONFIG = "remapper"
const val PLUGIN_REMAPPER_CONFIG = "pluginRemapper"
const val DECOMPILER_CONFIG = "decompiler"
const val PAPERCLIP_CONFIG = "paperclip"
const val DEV_BUNDLE_CONFIG = "paperweightDevelopmentBundle"
@ -89,12 +88,10 @@ const val PATCHED_SPIGOT_MOJANG_YARN_MAPPINGS = "$MAPPINGS_DIR/spigot-mojang+yar
const val PATCHED_SPIGOT_MOJANG_YARN_SOURCE_MAPPINGS = "$MAPPINGS_DIR/spigot-mojang+yarn-patched-source.tiny"
const val REOBF_MOJANG_SPIGOT_MAPPINGS = "$MAPPINGS_DIR/mojang+yarn-spigot-reobf.tiny"
const val PATCHED_REOBF_MOJANG_SPIGOT_MAPPINGS = "$MAPPINGS_DIR/mojang+yarn-spigot-reobf-patched.tiny"
const val RELOCATED_PATCHED_REOBF_MOJANG_SPIGOT_MAPPINGS = "$MAPPINGS_DIR/mojang+yarn-spigot-reobf-patched-relocated.tiny"
const val OBF_NAMESPACE = "official"
const val SPIGOT_NAMESPACE = "spigot"
const val DEOBF_NAMESPACE = "mojang+yarn"
const val MAPPINGS_NAMESPACE_MANIFEST_KEY = "paperweight-mappings-namespace"
private const val DATA_PATH = "$PAPER_PATH/data"
const val MC_MANIFEST = "$DATA_PATH/McManifest.json"
@ -117,6 +114,8 @@ const val MC_DEV_SOURCES_DIR = "$PAPER_PATH/mc-dev-sources"
const val IVY_REPOSITORY = "$PAPER_PATH/ivyRepository"
const val RELOCATION_EXTENSION = "relocation"
const val DOWNLOAD_SERVICE_NAME = "paperweightDownloadService"
fun paperSetupOutput(name: String, ext: String) = "$SETUP_CACHE/$name.$ext"

View file

@ -31,8 +31,8 @@ data class MavenArtifact(
private val group: String,
private val artifact: String,
private val version: String,
val classifier: String? = null,
val extension: String? = null
private val classifier: String? = null,
private val extension: String? = null
) {
private val classifierText: String
@ -46,9 +46,6 @@ data class MavenArtifact(
val file: String
get() = "$artifact-$version$classifierText.$ext"
val gav: String
get() = "$group:$artifact:$version"
fun downloadToFile(downloadService: DownloadService, targetFile: Path, repos: List<String>) {
targetFile.parent.createDirectories()

Some files were not shown because too many files have changed in this diff Show more