Skip to content

Commit

Permalink
add setupPaperScript task
Browse files Browse the repository at this point in the history
  • Loading branch information
MiniDigger committed Nov 1, 2024
1 parent 63d0471 commit 27f3010
Show file tree
Hide file tree
Showing 4 changed files with 224 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import io.papermc.paperweight.tasks.softspoon.ApplyFilePatches
import io.papermc.paperweight.tasks.softspoon.ApplyFilePatchesFuzzy
import io.papermc.paperweight.tasks.softspoon.FixupFilePatches
import io.papermc.paperweight.tasks.softspoon.RebuildFilePatches
import io.papermc.paperweight.tasks.softspoon.SetupPaperScript
import io.papermc.paperweight.util.*
import io.papermc.paperweight.util.constants.*
import io.papermc.paperweight.util.data.mache.*
Expand Down Expand Up @@ -243,6 +244,13 @@ open class SoftSpoonTasks(
repo.set(project.ext.serverProject.map { it.layout.projectDirectory.dir("src/vanilla/resources") })
}

val setupPaperScript by tasks.registering(SetupPaperScript::class) {
group = "softspoon"
description = "Creates a util script and installs it into path"

root.set(project.projectDir)
}

fun afterEvaluate() {
// load mache
mache = this.project.configurations.named(MACHE_CONFIG).get().singleFile.toPath().openZip().use { zip ->
Expand Down
13 changes: 0 additions & 13 deletions paperweight-core/src/test/kotlin/io/papermc/paperweight/util.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,8 @@
package io.papermc.paperweight

import io.papermc.paperweight.util.*
import java.nio.file.FileAlreadyExistsException
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.attribute.FileAttribute
import kotlin.io.path.*
import org.gradle.testkit.runner.GradleRunner

Expand All @@ -37,17 +35,6 @@ fun Path.copyProject(resourcesProjectName: String): ProjectFiles {
return ProjectFiles(this)
}

fun Path.createParentDirectories(vararg attributes: FileAttribute<*>): Path = also {
val parent = it.parent
if (parent != null && !parent.isDirectory()) {
try {
parent.createDirectories(*attributes)
} catch (e: FileAlreadyExistsException) {
if (!parent.isDirectory()) throw e
}
}
}

class ProjectFiles(val projectDir: Path) {
val gradleProperties: Path = resolve("gradle.properties")
val buildGradle: Path = resolve("build.gradle")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
package io.papermc.paperweight.tasks.softspoon

import io.papermc.paperweight.tasks.*
import io.papermc.paperweight.util.*
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.io.path.*
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.UntrackedTask
import org.gradle.api.tasks.options.Option

@UntrackedTask(because = "Always setup paper script")
abstract class SetupPaperScript : BaseTask() {

data class Command(val name: String, val aliases: List<String>, val description: String, val commands: List<String>)

@get:Input
@get:Option(
option = "script-name",
description = "Allows setting the script name. Default is paper.",
)
abstract val scriptName: Property<String>

@get:InputDirectory
abstract val root: DirectoryProperty

init {
run {
scriptName.convention("paper")
}
}

@TaskAction
open fun run() {
val scriptName = scriptName.get()
val rootPath = root.get().convertToPath().absolutePathString()
val commands = listOf(
Command("root", listOf(), "Jumps to the root directory (%root%)", listOf("cd %root%")),
Command("api", listOf("a"), "Jumps to the api directory", listOf("cd %root%/paper-api")),
Command("server", listOf("s"), "Jumps to the server directory", listOf("cd %root%/paper-server")),
Command("vanilla", listOf("v"), "Jumps to the vanilla directory", listOf("cd %root%/paper-server/src/vanilla/java")),
Command("resources", listOf("r"), "Jumps to the resources directory", listOf("cd %root%/paper-server/src/vanilla/resources")),
Command(
"fixupSourcePatches",
listOf("fs"),
"Puts the current source changes into the file patches commit",
listOf(
"cd %root%/paper-server/src/vanilla/java",
"git commit --fixup file",
"git -c sequence.editor=: rebase -i --autosquash mache/main"
)
),
Command(
"fixupResourcePatches",
listOf("fr"),
"Puts the current resource changes into the file patches commit",
listOf(
"cd %root%/paper-server/src/vanilla/resources",
"git commit --fixup file",
"git -c sequence.editor=: rebase -i --autosquash mache/main"
)
)
)

val isWindows = System.getProperty("os.name").lowercase().contains("win")
val script = generateScript(scriptName, rootPath, commands, isWindows)

if (isWindows) {
val appData = System.getenv("APPDATA")
val paperFolder = Path(appData).resolve(".paper")
val path = paperFolder.resolve("$scriptName.bat")
path.createParentDirectories()
path.writeText(script)

val alreadyOnPath = System.getenv("PATH").contains(paperFolder.absolutePathString())
if (!alreadyOnPath) {
val command = """
[Environment]::SetEnvironmentVariable(\"Path\", [Environment]::GetEnvironmentVariable(\"Path\", \"User\") + \";${paperFolder.absolutePathString()}\", \"User\")
""".trimIndent()
val process = Runtime.getRuntime().exec(arrayOf("powershell.exe", "-Command", command))
process.waitFor()
val reader = BufferedReader(InputStreamReader(process.inputStream))
val errorReader = BufferedReader(InputStreamReader(process.errorStream))

if (process.exitValue() != 0) {
reader.lines().forEach { println(it) }
errorReader.lines().forEach { println(it) }
println("Error while installing $scriptName script, please add \"${paperFolder.absolutePathString()}\" to PATH manually (exit code ${process.exitValue()})")
} else {
println("$scriptName script installed")
}
} else {
println("$scriptName script created")
}
} else {
val paperFolder = Path("~").resolve(".paper")
val path = paperFolder.resolve("$scriptName.sh")
path.createParentDirectories()
path.writeText(script)

val alreadyOnPath = System.getenv("PATH").contains(paperFolder.absolutePathString())
if (!alreadyOnPath) {
// TODO what do you want to do here?
println("setting up path for linux is not supported yet, add ${paperFolder.absolutePathString()} to your path manually pls")
} else {
println("$scriptName script created")
}
}
}

fun generateScript(scriptName: String, root: String, commands: List<Command>, isWindows: Boolean): String {
val script = StringBuilder()
val lineSeparator = if (isWindows) "\r\n" else "\n"
// header
val scriptHeader = if (isWindows) {
"@echo off$lineSeparator" + "goto:main$lineSeparator"
} else {
"#!/bin/bash$lineSeparator"
}
script.append(scriptHeader)
script.append(lineSeparator)

// help
if (isWindows) {
script.append(":help$lineSeparator")
script.append("setlocal EnableDelayedExpansion$lineSeparator")
script.append("set \"\"=\"$lineSeparator")
script.append("echo Available commands:$lineSeparator")
} else {
script.append("help() {$lineSeparator")
script.append(" echo \"Available commands:\"$lineSeparator")
}

commands.forEach { command ->
val aliases = command.aliases.joinToString(",", " (alias: ", ")")
val line = "$scriptName ${command.name}$aliases: ${command.description.replace("%root%", root)}"
if (isWindows) {
script.append("echo !\"!$line$lineSeparator")
} else {
script.append(" echo \"$line\"$lineSeparator")
}
}

if (isWindows) {
script.append("goto:eof$lineSeparator")
} else {
script.append("}$lineSeparator")
}
script.append(lineSeparator)

// commands
commands.forEach { command ->
if (isWindows) {
script.append(":${command.name}$lineSeparator")
command.commands.forEach { cmd ->
script.append("${cmd.replace("%root%", root)}$lineSeparator")
}
script.append("goto:eof$lineSeparator")
command.aliases.forEach { alias ->
script.append(":$alias$lineSeparator")
script.append("call:${command.name}$lineSeparator")
script.append("goto:eof$lineSeparator")
}
} else {
script.append("${command.name}() {$lineSeparator")
command.commands.forEach { cmd ->
script.append(" ${cmd.replace("%root%", root)}$lineSeparator")
}
script.append("}$lineSeparator")
command.aliases.forEach { alias ->
script.append("$alias() {$lineSeparator")
script.append(" ${command.name}$lineSeparator")
script.append("}$lineSeparator")
}
}
script.append(lineSeparator)
}

// main
if (isWindows) {
script.append(":main$lineSeparator")
script.append("if \"%1\"==\"\" ($lineSeparator")
script.append(" echo No command provided, try $scriptName help$lineSeparator")
script.append(" exit /b 1$lineSeparator")
script.append(")$lineSeparator")
script.append(lineSeparator)
script.append("call:%1$lineSeparator")
} else {
script.append("if [ \$# -eq 0 ]; then$lineSeparator")
script.append(" echo \"No command provided, try $scriptName help\"$lineSeparator")
script.append(" exit 1$lineSeparator")
script.append("fi$lineSeparator")
script.append(lineSeparator)
script.append("\"$@\"$lineSeparator")
}

return script.toString()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,15 @@ package io.papermc.paperweight.util
import io.papermc.paperweight.PaperweightException
import java.io.InputStream
import java.net.URI
import java.nio.file.FileAlreadyExistsException
import java.nio.file.FileSystem
import java.nio.file.FileSystemNotFoundException
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.PathMatcher
import java.nio.file.attribute.DosFileAttributeView
import java.nio.file.attribute.FileAttribute
import java.util.Arrays
import java.util.stream.Collectors
import java.util.stream.Stream
Expand Down Expand Up @@ -289,3 +291,14 @@ private fun relativeCopyOrMove(baseDir: Path, file: Path, outputDir: Path, move:
file.copyTo(destination, overwrite = true)
}
}

fun Path.createParentDirectories(vararg attributes: FileAttribute<*>): Path = also {
val parent = it.parent
if (parent != null && !parent.isDirectory()) {
try {
parent.createDirectories(*attributes)
} catch (e: FileAlreadyExistsException) {
if (!parent.isDirectory()) throw e
}
}
}

0 comments on commit 27f3010

Please sign in to comment.