Initial commit.

This commit is contained in:
Logan Gorence
2022-07-09 18:14:21 -07:00
commit e35c682c2e
18 changed files with 721 additions and 0 deletions

View File

@ -0,0 +1,8 @@
package lgbt.mystic.foundation.concrete
import org.gradle.api.provider.Property
interface ConcreteExtension {
val paperVersionGroup: Property<String>
val minecraftServerPath: Property<String>
}

View File

@ -0,0 +1,25 @@
package lgbt.mystic.foundation.concrete
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.create
class ConcreteGradlePlugin : Plugin<Project> {
override fun apply(project: Project) {
project.extensions.create<ConcreteExtension>("concrete")
val setupPaperServer = project.tasks.create<SetupPaperServer>("setupPaperServer")
project.afterEvaluate { ->
setupPaperServer.dependsOn(*project.subprojects
// TODO: Foundation specific
.filter { it.isFoundationPlugin() }
.map { it.tasks.getByName("shadowJar") }
.toTypedArray()
)
}
val runPaperServer = project.tasks.create<RunPaperServer>("runPaperServer")
runPaperServer.dependsOn(setupPaperServer)
val updateManifests = project.tasks.create<UpdateManifestTask>("updateManifests")
project.tasks.getByName("assemble").dependsOn(updateManifests)
}
}

View File

@ -0,0 +1,16 @@
package lgbt.mystic.foundation.concrete
import org.gradle.api.Plugin
import org.gradle.api.Project
class ConcreteProjectPlugin : Plugin<Project> {
override fun apply(project: Project) {
val versionWithBuild = if (System.getenv("CI_PIPELINE_IID") != null) {
project.rootProject.version.toString() + ".${System.getenv("CI_PIPELINE_IID")}"
} else {
"DEV"
}
project.version = versionWithBuild
}
}

View File

@ -0,0 +1,7 @@
package lgbt.mystic.foundation.concrete
import com.google.gson.Gson
object Globals {
val gson = Gson()
}

View File

@ -0,0 +1,46 @@
package lgbt.mystic.foundation.concrete
import com.google.gson.Gson
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
class PaperVersionClient(
val client: HttpClient = HttpClient.newHttpClient(),
private val gson: Gson = Globals.gson
) {
private val apiBaseUrl = URI.create("https://papermc.io/api/v2/")
fun getVersionBuilds(group: String): List<PaperBuild> {
val response = client.send(
HttpRequest.newBuilder()
.GET()
.uri(apiBaseUrl.resolve("projects/paper/version_group/${group}/builds"))
.build(),
HttpResponse.BodyHandlers.ofString()
)
val body = response.body()
val root = gson.fromJson(body, PaperVersionRoot::class.java)
return root.builds
}
fun resolveDownloadUrl(build: PaperBuild, download: PaperVersionDownload): URI =
apiBaseUrl.resolve("projects/paper/versions/${build.version}/builds/${build.build}/downloads/${download.name}")
data class PaperVersionRoot(
val builds: List<PaperBuild>
)
data class PaperBuild(
val version: String,
val build: Int,
val downloads: Map<String, PaperVersionDownload>
)
data class PaperVersionDownload(
val name: String,
val sha256: String
)
}

View File

@ -0,0 +1,33 @@
package lgbt.mystic.foundation.concrete
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.getByType
import java.io.File
import java.util.jar.JarFile
open class RunPaperServer : DefaultTask() {
init {
outputs.upToDateWhen { false }
}
@TaskAction
fun runPaperServer() {
val concrete = project.extensions.getByType<ConcreteExtension>()
val minecraftServerDirectory = project.file(concrete.minecraftServerPath.get())
val paperJarFile = minecraftServerDirectory.resolve("paper.jar")
val mainClassName = readMainClass(paperJarFile)
project.javaexec {
classpath(paperJarFile.absolutePath)
workingDir(minecraftServerDirectory)
args("nogui")
mainClass.set(mainClassName)
}
}
private fun readMainClass(file: File): String = JarFile(file).use { jar ->
jar.manifest.mainAttributes.getValue("Main-Class")!!
}
}

View File

@ -0,0 +1,69 @@
package lgbt.mystic.foundation.concrete
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
import org.gradle.kotlin.dsl.getByType
import java.io.File
import java.nio.file.Files
open class SetupPaperServer : DefaultTask() {
init {
outputs.upToDateWhen { false }
}
@get:Input
@set:Option(option = "update", description = "Update Paper Server")
var shouldUpdatePaperServer = false
private val paperVersionClient = PaperVersionClient()
@TaskAction
fun downloadPaperTask() {
val concrete = project.extensions.getByType<ConcreteExtension>()
val minecraftServerDirectory = project.file(concrete.minecraftServerPath.get())
if (!minecraftServerDirectory.exists()) {
minecraftServerDirectory.mkdirs()
}
val paperJarFile = project.file("${concrete.minecraftServerPath.get()}/paper.jar")
if (!paperJarFile.exists() || shouldUpdatePaperServer) {
downloadLatestBuild(concrete.paperVersionGroup.get(), paperJarFile)
}
val paperPluginsDirectory = minecraftServerDirectory.resolve("plugins")
if (!paperPluginsDirectory.exists()) {
paperPluginsDirectory.mkdirs()
}
for (project in project.subprojects) {
if (!project.isFoundationPlugin()) {
continue
}
val pluginJarFile = project.buildDir.resolve("libs/${project.name}-DEV-plugin.jar")
val pluginLinkFile = paperPluginsDirectory.resolve("${project.name}.jar")
if (pluginLinkFile.exists()) {
pluginLinkFile.delete()
}
Files.createSymbolicLink(pluginLinkFile.toPath(), pluginJarFile.toPath())
}
}
private fun downloadLatestBuild(paperVersionGroup: String, paperJarFile: File) {
val builds = paperVersionClient.getVersionBuilds(paperVersionGroup)
val build = builds.last()
val download = build.downloads["application"]!!
val url = paperVersionClient.resolveDownloadUrl(build, download)
val downloader = SmartDownloader(paperJarFile.toPath(), url, download.sha256)
if (downloader.download()) {
logger.lifecycle("Installed Paper Server ${build.version} build ${build.build}")
} else {
logger.lifecycle("Paper Server ${build.version} build ${build.build} is up-to-date")
}
}
}

View File

@ -0,0 +1,78 @@
package lgbt.mystic.foundation.concrete
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import java.security.MessageDigest
class SmartDownloader(
private val localFilePath: Path,
private val remoteDownloadUrl: URI,
private val sha256: String
) {
fun download(): Boolean {
val hashResult = checkLocalFileHash()
if (hashResult != HashResult.ValidHash) {
downloadRemoteFile()
return false
}
return true
}
private fun downloadRemoteFile() {
val url = remoteDownloadUrl.toURL()
val remoteFileStream = url.openStream()
val localFileStream = Files.newOutputStream(localFilePath)
remoteFileStream.transferTo(localFileStream)
val hashResult = checkLocalFileHash()
if (hashResult != HashResult.ValidHash) {
throw RuntimeException("Download of $remoteDownloadUrl did not result in valid hash.")
}
}
private fun checkLocalFileHash(): HashResult {
if (!Files.exists(localFilePath)) {
return HashResult.DoesNotExist
}
val digest = MessageDigest.getInstance("SHA-256")
val localFileStream = Files.newInputStream(localFilePath)
val buffer = ByteArray(16 * 1024)
while (true) {
val size = localFileStream.read(buffer)
if (size <= 0) {
break
}
val bytes = buffer.take(size).toByteArray()
digest.update(bytes)
}
val sha256Bytes = digest.digest()
val localSha256Hash = bytesToHex(sha256Bytes)
return if (localSha256Hash.equals(sha256, ignoreCase = true)) {
HashResult.ValidHash
} else {
HashResult.InvalidHash
}
}
private fun bytesToHex(hash: ByteArray): String {
val hexString = StringBuilder(2 * hash.size)
for (i in hash.indices) {
val hex = Integer.toHexString(0xff and hash[i].toInt())
if (hex.length == 1) {
hexString.append('0')
}
hexString.append(hex)
}
return hexString.toString()
}
enum class HashResult {
DoesNotExist,
InvalidHash,
ValidHash
}
}

View File

@ -0,0 +1,32 @@
package lgbt.mystic.foundation.concrete
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import java.nio.file.Files
import java.nio.file.Path
open class UpdateManifestTask : DefaultTask() {
@TaskAction
fun update() {
val manifestsDir = ensureManifestsDir()
val updateFile = manifestsDir.resolve("update.json")
val rootPath = project.rootProject.rootDir.toPath()
val updateManifest = project.findPluginProjects().mapNotNull { project ->
val paths = project.shadowJarOutputs.allFilesRelativeToPath(rootPath)
if (paths.isNotEmpty()) {
project.name to mapOf(
"version" to project.version,
"artifacts" to paths.map { it.toUnixString() }
)
} else null
}.toMap()
Files.writeString(updateFile, Globals.gson.toJson(updateManifest))
}
private fun ensureManifestsDir(): Path {
val manifestsDir = project.buildDir.resolve("manifests")
manifestsDir.mkdirs()
return manifestsDir.toPath()
}
}

View File

@ -0,0 +1,17 @@
package lgbt.mystic.foundation.concrete
import org.gradle.api.Project
import org.gradle.api.tasks.TaskOutputs
import java.nio.file.FileSystems
import java.nio.file.Path
fun Project.isFoundationPlugin() = name.startsWith("foundation-")
fun Project.findPluginProjects() = rootProject.subprojects.filter { project -> project.isFoundationPlugin() }
val Project.shadowJarOutputs: TaskOutputs
get() = project.tasks.getByName("shadowJar").outputs
fun TaskOutputs.allFilesRelativeToPath(root: Path): List<Path> = files.map { root.relativize(it.toPath()) }
fun Path.toUnixString() = toString().replace(FileSystems.getDefault().separator, "/")