Skip to content

Commit

Permalink
allow to optionally apply/format source patches using git
Browse files Browse the repository at this point in the history
  • Loading branch information
MiniDigger committed Nov 2, 2024
1 parent af1bbec commit f941ce4
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ open class PaperweightCoreExtension(project: Project, objects: ObjectFactory, la
val macheRepo: Property<String> = objects.property<String>().convention("https://repo.papermc.io/repository/maven-public/")

val macheOldPath: DirectoryProperty = objects.directoryProperty()
val gitFilePatches: Property<Boolean> = objects.property<Boolean>().convention(false)

val vanillaJarIncludes: ListProperty<String> = objects.listProperty<String>().convention(
listOf("/*.class", "/net/minecraft/**", "/com/mojang/math/**")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ open class SoftSpoonTasks(
output.set(project.ext.serverProject.map { it.layout.projectDirectory.dir("src/vanilla/java") })
patches.set(project.ext.paper.sourcePatchDir)
rejects.set(project.ext.paper.rejectsDir)
gitFilePatches.set(project.ext.gitFilePatches)
}

val applySourcePatchesFuzzy by tasks.registering(ApplyFilePatchesFuzzy::class) {
Expand All @@ -155,6 +156,7 @@ open class SoftSpoonTasks(
output.set(project.ext.serverProject.map { it.layout.projectDirectory.dir("src/vanilla/java") })
patches.set(project.ext.paper.sourcePatchDir)
rejects.set(project.ext.paper.rejectsDir)
gitFilePatches.set(project.ext.gitFilePatches)
}

val applyResourcePatches by tasks.registering(ApplyFilePatches::class) {
Expand Down Expand Up @@ -198,6 +200,7 @@ open class SoftSpoonTasks(
base.set(layout.cache.resolve(BASE_PROJECT).resolve("sources"))
input.set(project.ext.serverProject.map { it.layout.projectDirectory.dir("src/vanilla/java") })
patches.set(project.ext.paper.sourcePatchDir)
gitFilePatches.set(project.ext.gitFilePatches)
}

val rebuildResourcePatches by tasks.registering(RebuildFilePatches::class) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import io.papermc.paperweight.tasks.*
import io.papermc.paperweight.util.*
import java.io.PrintStream
import java.nio.file.Path
import java.time.Instant
import kotlin.io.path.*
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.PersonIdent
Expand Down Expand Up @@ -64,9 +65,14 @@ abstract class ApplyFilePatches : BaseTask() {
@get:OutputDirectory
abstract val rejects: DirectoryProperty

@get:Optional
@get:Input
abstract val gitFilePatches: Property<Boolean>

init {
run {
verbose.convention(false)
gitFilePatches.convention(false)
}
}

Expand All @@ -81,6 +87,31 @@ abstract class ApplyFilePatches : BaseTask() {

setupGitHook(outputPath)

val result = if (gitFilePatches.get()) {
applyWithGit(outputPath)
} else {
applyWithDiffPatch()
}

if (!verbose.get()) {
logger.lifecycle("Applied $result patches")
}
}

private fun applyWithGit(outputPath: Path): Int {
val git = Git(outputPath)
val patches = patches.convertToPath().filesMatchingRecursive("*.patch")
val patchStrings = patches.map { outputPath.relativize(it).pathString }
patchStrings.chunked(12).forEach {
git("apply", "--3way", *it.toTypedArray()).executeSilently(silenceOut = !verbose.get(), silenceErr = !verbose.get())
}

commit()

return patches.size
}

private fun applyWithDiffPatch(): Int {
val printStream = PrintStream(LoggingOutputStream(logger, LogLevel.LIFECYCLE))
val builder = PatchOperation.builder()
.logTo(printStream)
Expand All @@ -96,6 +127,7 @@ abstract class ApplyFilePatches : BaseTask() {
if (rejects.isPresent) {
builder.rejectsPath(rejects.convertToPath())
}

val result = builder.build().operate()

commit()
Expand All @@ -106,9 +138,7 @@ abstract class ApplyFilePatches : BaseTask() {
throw Exception("Failed to apply ${result.summary.failedMatches}/$total hunks")
}

if (!verbose.get()) {
logger.lifecycle("Applied ${result.summary.changedFiles} patches")
}
return result.summary.changedFiles
}

private fun setupGitHook(outputPath: Path) {
Expand All @@ -119,7 +149,7 @@ abstract class ApplyFilePatches : BaseTask() {
}

private fun commit() {
val ident = PersonIdent("File", "[email protected]")
val ident = PersonIdent(PersonIdent("File", "[email protected]"), Instant.parse("1997-04-20T13:37:42.69Z"))
val git = Git.open(output.convertToPath().toFile())
git.add().addFilepattern(".").call()
git.commit()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,14 @@ abstract class RebuildFilePatches : BaseTask() {
@get:Input
abstract val contextLines: Property<Int>

@get:Optional
@get:Input
abstract val gitFilePatches: Property<Boolean>

override fun init() {
contextLines.convention(3)
verbose.convention(false)
gitFilePatches.convention(false)
}

@TaskAction
Expand Down Expand Up @@ -136,27 +141,18 @@ abstract class RebuildFilePatches : BaseTask() {
}

// rebuild patches
val printStream = PrintStream(LoggingOutputStream(logger, org.gradle.api.logging.LogLevel.LIFECYCLE))
val result = DiffOperation.builder()
.logTo(printStream)
.aPath(baseDir)
.bPath(inputDir)
.outputPath(patchDir)
.autoHeader(true)
.level(if (verbose.get()) LogLevel.ALL else LogLevel.INFO)
.lineEnding("\n")
.ignorePrefix(".git")
.ignorePrefix("data/minecraft/structures")
.ignorePrefix("data/.mc")
.ignorePrefix("assets/.mc")
.context(contextLines.get())
.summary(verbose.get())
.build()
.operate()
val result = if (gitFilePatches.get()) {
rebuildWithGit(git, patchDir)
} else {
rebuildWithDiffPatch(baseDir, inputDir, patchDir)
}

git("switch", "-").executeSilently(silenceErr = true)
if (filesWithNewAts.isNotEmpty()) {
try {
// we need to rebase, so that the new file commit is part of the tree again.
// for that we use GIT_SEQUENCE_EDITOR to drop the first commit
// and then execs for all the files that remove the papter
// todo detect if sed is not present (windows) and switch out sed for something else
@Language("Shell Script")
val sequenceEditor = "sed -i -e 0,/pick/{s/pick/drop/}"
Expand All @@ -176,7 +172,59 @@ abstract class RebuildFilePatches : BaseTask() {
val patchDirGit = Git(patchDir)
patchDirGit("add", "-A", ".").executeSilently()

logger.lifecycle("Rebuilt ${result.summary.changedFiles} patches")
logger.lifecycle("Rebuilt $result patches")
}

private fun rebuildWithGit(
git: Git,
patchDir: Path
): Int {
val files = git("diff-tree", "--name-only", "--no-commit-id", "-r", "HEAD").getText().split("\n")
files.parallelStream().forEach { filename ->
if (filename.isBlank()) return@forEach
val patch = git(
"format-patch",
"--diff-algorithm=myers",
"--full-index",
"--no-signature",
"--no-stat",
"--no-numbered",
"-1",
"HEAD",
"--stdout",
filename
).getText()
val patchFile = patchDir.resolve("$filename.patch")
patchFile.createParentDirectories()
patchFile.writeText(patch)
}

return files.size
}

private fun rebuildWithDiffPatch(
baseDir: Path,
inputDir: Path,
patchDir: Path
): Int {
val printStream = PrintStream(LoggingOutputStream(logger, org.gradle.api.logging.LogLevel.LIFECYCLE))
val result = DiffOperation.builder()
.logTo(printStream)
.aPath(baseDir)
.bPath(inputDir)
.outputPath(patchDir)
.autoHeader(true)
.level(if (verbose.get()) LogLevel.ALL else LogLevel.INFO)
.lineEnding("\n")
.ignorePrefix(".git")
.ignorePrefix("data/minecraft/structures")
.ignorePrefix("data/.mc")
.ignorePrefix("assets/.mc")
.context(contextLines.get())
.summary(verbose.get())
.build()
.operate()
return result.summary.changedFiles
}

private fun handleATInBase(decomp: Path, newAts: AccessTransformSet, decompRoot: Path) {
Expand Down

0 comments on commit f941ce4

Please sign in to comment.