mirror of
https://github.com/darksaid98/Carbon.git
synced 2026-12-02 06:28:54 +00:00
Download dependencies at runtime on all platforms (not just Paper), and read dependency info from file in plugin jar generated by Gradle task (#259)
* Download dependencies at runtime on all platforms (not just Paper), and read dependency info from file in plugin jar generated by Gradle task * Add maven central as fallback for paper mirror * filter duplicate dependencies * fix fabric runServer * add todo * enable hangar publishing * - exclude unneeded deps from runtime dl - sort deps and relocations in the list file - other misc fixes * move jdbi relocation * don't log anything when we don't download or relocate any dependencies * add back mariadb driver and download more dependencies at runtime and other related build changes * build cleanup * build cleanup * remove useless dependencies block
This commit is contained in:
1 parent
82c22a08fa
commit
307395ce5b
16 files changed
+694
-95
No files matched your search
@@ -77,12 +77,12 @@ jobs:
|
||||
env:
|
||||
MODRINTH_TOKEN: "${{ secrets.MODRINTH_TOKEN }}"
|
||||
RELEASE_NOTES: "${{ github.event.release.body }}"
|
||||
# - name: Publish (Pre-)Release to Hangar
|
||||
# if: "${{ env.STATUS == 'release' && github.event_name == 'release' }}"
|
||||
# run: ./gradlew publishAllPublicationsToHangar
|
||||
# env:
|
||||
# HANGAR_UPLOAD_KEY: "${{ secrets.HANGAR_UPLOAD_KEY }}"
|
||||
# RELEASE_NOTES: "${{ github.event.release.body }}"
|
||||
- name: Publish (Pre-)Release to Hangar
|
||||
if: "${{ env.STATUS == 'release' && github.event_name == 'release' }}"
|
||||
run: ./gradlew publishAllPublicationsToHangar
|
||||
env:
|
||||
HANGAR_UPLOAD_KEY: "${{ secrets.HANGAR_UPLOAD_KEY }}"
|
||||
RELEASE_NOTES: "${{ github.event.release.body }}"
|
||||
- name: Upload Artifacts
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import org.gradle.api.model.ObjectFactory
|
||||
import org.gradle.api.provider.Property
|
||||
import org.gradle.kotlin.dsl.property
|
||||
import javax.inject.Inject
|
||||
|
||||
abstract class CarbonShadowPlatformExtension @Inject constructor(objects: ObjectFactory) {
|
||||
val relocateGuice: Property<Boolean> = objects.property<Boolean>().convention(false)
|
||||
val relocateCloud: Property<Boolean> = objects.property<Boolean>().convention(true)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import org.gradle.api.DefaultTask
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.artifacts.component.ModuleComponentIdentifier
|
||||
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
|
||||
import org.gradle.api.artifacts.result.DependencyResult
|
||||
import org.gradle.api.artifacts.result.ResolvedComponentResult
|
||||
import org.gradle.api.artifacts.result.ResolvedDependencyResult
|
||||
import org.gradle.api.file.ConfigurableFileCollection
|
||||
import org.gradle.api.file.DirectoryProperty
|
||||
import org.gradle.api.initialization.Settings
|
||||
import org.gradle.api.internal.GradleInternal
|
||||
import org.gradle.api.provider.ListProperty
|
||||
import org.gradle.api.provider.Property
|
||||
import org.gradle.api.tasks.Input
|
||||
import org.gradle.api.tasks.InputFiles
|
||||
import org.gradle.api.tasks.OutputDirectory
|
||||
import org.gradle.api.tasks.TaskAction
|
||||
|
||||
abstract class WriteDependencies : DefaultTask() {
|
||||
@get:Input
|
||||
abstract val tree: Property<ResolvedComponentResult>
|
||||
|
||||
@get:InputFiles
|
||||
abstract val files: ConfigurableFileCollection
|
||||
|
||||
@get:Input
|
||||
abstract val outputFileName: Property<String>
|
||||
|
||||
@get:OutputDirectory
|
||||
abstract val outputDir: DirectoryProperty
|
||||
|
||||
@get:Input
|
||||
abstract val repos: ListProperty<String>
|
||||
|
||||
@get:Input
|
||||
abstract val transitive: Property<Boolean>
|
||||
|
||||
@get:Input
|
||||
abstract val relocations: ListProperty<String>
|
||||
|
||||
init {
|
||||
init()
|
||||
}
|
||||
|
||||
private fun init() {
|
||||
transitive.convention(true)
|
||||
}
|
||||
|
||||
fun relocate(from: String, to: String) {
|
||||
relocations.add("$from $to")
|
||||
}
|
||||
|
||||
@TaskAction
|
||||
fun run() {
|
||||
val outputLines = StringBuilder()
|
||||
val outputFile = outputDir.get().file(outputFileName.get()).asFile
|
||||
val files = files.files
|
||||
for (repo in repos()) {
|
||||
outputLines.append(repo).append("\n")
|
||||
}
|
||||
outputLines.append("end_repos\n")
|
||||
for (dependency in deps()) {
|
||||
val id = dependency.resolvedVariant.owner as ModuleComponentIdentifier
|
||||
val file = files.single { it.name.equals("${id.module}-${id.version}.jar") }
|
||||
outputLines.append(id.displayName).append(" ").append(file.toPath().hashFile(HashingAlgorithm.SHA256).asHexString()).append("\n")
|
||||
}
|
||||
outputLines.append("end_deps\n")
|
||||
for (r in relocations.get().sorted()) {
|
||||
outputLines.append(r).append("\n")
|
||||
}
|
||||
outputFile.parentFile.mkdirs()
|
||||
outputFile.delete()
|
||||
outputFile.writeText(outputLines.toString())
|
||||
}
|
||||
|
||||
private fun repos(): List<String> {
|
||||
if (repos.get().isNotEmpty()) {
|
||||
return repos.get()
|
||||
}
|
||||
if (project.repositories.isNotEmpty()) {
|
||||
return project.repositories.mapNotNull { (it as? MavenArtifactRepository)?.url.toString() }
|
||||
}
|
||||
return project.settings.dependencyResolutionManagement.repositories.mapNotNull { (it as? MavenArtifactRepository)?.url.toString() }
|
||||
}
|
||||
|
||||
private val Project.settings: Settings
|
||||
get() = (gradle as GradleInternal).settings
|
||||
|
||||
private fun deps(): List<ResolvedDependencyResult> {
|
||||
val set = mutableSetOf<ResolvedDependencyResult>()
|
||||
set.addFrom(tree.get().dependencies)
|
||||
return set.associateBy { it.resolvedVariant.owner.displayName }
|
||||
.map { it.value }
|
||||
.sortedBy { it.resolvedVariant.owner.displayName }
|
||||
}
|
||||
|
||||
private fun MutableSet<ResolvedDependencyResult>.addFrom(dependencies: Set<DependencyResult>) {
|
||||
for (dependency in dependencies) {
|
||||
dependency as ResolvedDependencyResult
|
||||
add(dependency)
|
||||
if (transitive.get()) {
|
||||
addFrom(dependency.selected.dependencies)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,37 @@ plugins {
|
||||
id("com.modrinth.minotaur")
|
||||
}
|
||||
|
||||
val runtimeDownload: Configuration by configurations.creating {
|
||||
isCanBeResolved = true
|
||||
isCanBeConsumed = false
|
||||
attributes {
|
||||
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME))
|
||||
}
|
||||
|
||||
exclude("org.checkerframework", "checker-qual")
|
||||
exclude("org.slf4j", "slf4j-api")
|
||||
exclude("com.google.errorprone", "error_prone_annotations")
|
||||
exclude("io.leangen.geantyref", "geantyref")
|
||||
}
|
||||
|
||||
val platformExtension = extensions.create<CarbonPlatformExtension>("carbonPlatform")
|
||||
|
||||
dependencies {
|
||||
runtimeDownload(libs.postgresql)
|
||||
runtimeDownload(libs.mariadb)
|
||||
runtimeDownload(libs.zstdjni)
|
||||
runtimeDownload(libs.jdbiCore)
|
||||
runtimeDownload(libs.jdbiObject)
|
||||
runtimeDownload(libs.jdbiPostgres)
|
||||
runtimeDownload(libs.caffeine)
|
||||
runtimeDownload(libs.jedis)
|
||||
runtimeDownload(libs.rabbitmq)
|
||||
runtimeDownload(libs.nats)
|
||||
runtimeDownload(libs.assistedInject) {
|
||||
isTransitive = false
|
||||
}
|
||||
}
|
||||
|
||||
tasks {
|
||||
val copyJar = register<FileCopyTask>("copyJar") {
|
||||
fileToCopy.set(platformExtension.jarTask.flatMap { it.archiveFile })
|
||||
@@ -30,6 +59,21 @@ modrinth {
|
||||
gameVersions.addAll("1.19.4", "1.20.1")
|
||||
}
|
||||
|
||||
val writeDeps = tasks.register("writeDependencies", WriteDependencies::class) {
|
||||
tree.set(runtimeDownload.incoming.resolutionResult.rootComponent)
|
||||
files.from(runtimeDownload)
|
||||
outputFileName.set("carbon-dependencies.list")
|
||||
outputDir.set(layout.buildDirectory.dir("generated/dependencyList"))
|
||||
repos.add("https://repo.papermc.io/repository/maven-public/")
|
||||
repos.add("https://repo.maven.apache.org/maven2/")
|
||||
}
|
||||
|
||||
sourceSets.main {
|
||||
resources {
|
||||
srcDir(writeDeps)
|
||||
}
|
||||
}
|
||||
|
||||
//val projectVersion = version as String
|
||||
//if (projectVersion.endsWith("-SNAPSHOT")) {
|
||||
// // Add git commit hash to version for platforms
|
||||
|
||||
@@ -3,8 +3,6 @@ plugins {
|
||||
id("com.github.johnrengelman.shadow")
|
||||
}
|
||||
|
||||
val shadowPlatform = extensions.create<CarbonShadowPlatformExtension>("carbonShadowPlatform")
|
||||
|
||||
tasks {
|
||||
jar {
|
||||
archiveClassifier.set("unshaded")
|
||||
@@ -19,14 +17,3 @@ tasks {
|
||||
extensions.configure<CarbonPlatformExtension> {
|
||||
jarTask.set(tasks.shadowJar)
|
||||
}
|
||||
|
||||
afterEvaluate {
|
||||
tasks.shadowJar {
|
||||
if (shadowPlatform.relocateGuice.get()) {
|
||||
relocateGuice()
|
||||
}
|
||||
if (shadowPlatform.relocateCloud.get()) {
|
||||
relocateCloud()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,23 +2,52 @@ import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||
import net.kyori.indra.git.IndraGitExtension
|
||||
import org.gradle.accessors.dm.LibrariesForLibs
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.Task
|
||||
import org.gradle.api.provider.Provider
|
||||
import org.gradle.kotlin.dsl.the
|
||||
|
||||
val Project.releaseNotes: Provider<String>
|
||||
get() = providers.environmentVariable("RELEASE_NOTES")
|
||||
|
||||
fun Task.relocateDependency(pkg: String) {
|
||||
when (this) {
|
||||
is ShadowJar -> relocateDependency(pkg)
|
||||
is WriteDependencies -> relocateDependency(pkg)
|
||||
else -> error("relocateDependency must be called on a ShadowJar or WriteDependencies task, not ${this.javaClass.name}")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Relocate a package into the `net.draycia.carbon.libs` namespace.
|
||||
* Relocate a package into the `carbonchat.libs.` namespace.
|
||||
*/
|
||||
fun ShadowJar.relocateDependency(pkg: String) {
|
||||
relocate(pkg, "net.draycia.carbon.libs.$pkg")
|
||||
relocate(pkg, "carbonchat.libs.$pkg")
|
||||
}
|
||||
|
||||
fun WriteDependencies.relocateDependency(pkg: String) {
|
||||
relocate(pkg, "carbonchat.libs.$pkg")
|
||||
}
|
||||
|
||||
fun Task.standardRuntimeRelocations() {
|
||||
relocateDependency("com.github.benmanes")
|
||||
relocateDependency("com.github.luben.zstd")
|
||||
relocateDependency("com.google.protobuf")
|
||||
relocateDependency("com.mysql.cj")
|
||||
relocateDependency("com.mysql.jdbc")
|
||||
relocateDependency("com.rabbitmq")
|
||||
relocateDependency("io.nats")
|
||||
relocateDependency("net.i2p.crypto")
|
||||
relocateDependency("org.apache.commons.pool2")
|
||||
relocateDependency("org.jdbi")
|
||||
relocateDependency("org.mariadb.jdbc")
|
||||
relocateDependency("org.postgresql")
|
||||
relocateDependency("redis.clients.jedis")
|
||||
}
|
||||
|
||||
/**
|
||||
* Relocates dependencies which we bundle and relocate on all platforms.
|
||||
*/
|
||||
fun ShadowJar.standardRelocations() {
|
||||
fun Task.standardRelocations() {
|
||||
relocateDependency("org.bstats")
|
||||
relocateDependency("net.kyori.adventure.serializer.configurate4")
|
||||
relocateDependency("com.seiama.event")
|
||||
@@ -27,25 +56,18 @@ fun ShadowJar.standardRelocations() {
|
||||
relocateDependency("org.spongepowered.configurate")
|
||||
relocateDependency("com.typesafe.config")
|
||||
relocateDependency("com.google.thirdparty.publicsuffix")
|
||||
relocateDependency("org.jdbi")
|
||||
relocateDependency("com.github.benmanes")
|
||||
relocateDependency("com.zaxxer.hikari")
|
||||
relocateDependency("redis.clients.jedis")
|
||||
relocateDependency("ninja.egg82.messenger")
|
||||
relocateDependency("org.antlr")
|
||||
relocateDependency("io.nats")
|
||||
relocateDependency("com.rabbitmq")
|
||||
relocateDependency("com.electronwill")
|
||||
relocateDependency("net.i2p.crypto")
|
||||
relocateDependency("org.apache.commons.pool2")
|
||||
relocateDependency("org.flywaydb")
|
||||
}
|
||||
|
||||
fun ShadowJar.relocateCloud() {
|
||||
fun Task.relocateCloud() {
|
||||
relocateDependency("cloud.commandframework")
|
||||
}
|
||||
|
||||
fun ShadowJar.relocateGuice() {
|
||||
fun Task.relocateGuice() {
|
||||
relocateDependency("com.google.inject")
|
||||
relocateDependency("org.aopalliance")
|
||||
relocateDependency("javax.inject")
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import java.io.InputStream
|
||||
import java.nio.file.Path
|
||||
import java.security.DigestInputStream
|
||||
import java.security.MessageDigest
|
||||
import kotlin.io.path.inputStream
|
||||
|
||||
enum class HashingAlgorithm(algorithm: String) {
|
||||
SHA256("SHA-256"),
|
||||
SHA1("SHA-1");
|
||||
|
||||
private val threadLocalMessageDigest = ThreadLocal.withInitial { MessageDigest.getInstance(algorithm) }
|
||||
|
||||
val digest: MessageDigest
|
||||
get() = threadLocalMessageDigest.get()
|
||||
}
|
||||
|
||||
fun Path.hashFile(algorithm: HashingAlgorithm): ByteArray = inputStream().use { input -> input.hash(algorithm) }
|
||||
|
||||
fun InputStream.hash(algorithm: HashingAlgorithm): ByteArray {
|
||||
val digestStream = DigestInputStream(this, algorithm.digest)
|
||||
digestStream.use { stream ->
|
||||
val buffer = ByteArray(1024)
|
||||
while (stream.read(buffer) != -1) {
|
||||
// reading
|
||||
}
|
||||
}
|
||||
return digestStream.messageDigest.digest()
|
||||
}
|
||||
|
||||
fun ByteArray.asHexString(): String {
|
||||
val sb: StringBuilder = StringBuilder(size * 2)
|
||||
for (aHash in this) {
|
||||
sb.append("%02x".format(aHash.toInt() and 0xFF))
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
+11
-10
@@ -20,30 +20,31 @@ dependencies {
|
||||
}
|
||||
|
||||
// Other
|
||||
api(libs.guice) {
|
||||
compileOnlyApi(libs.guice) {
|
||||
exclude("com.google.guava")
|
||||
}
|
||||
api(libs.assistedInject)
|
||||
compileOnlyApi(libs.assistedInject) {
|
||||
isTransitive = false
|
||||
}
|
||||
compileOnlyApi(libs.luckPermsApi)
|
||||
|
||||
// Storage
|
||||
api(libs.jdbiCore)
|
||||
api(libs.jdbiObject)
|
||||
api(libs.jdbiPostgres)
|
||||
compileOnlyApi(libs.jdbiCore)
|
||||
compileOnlyApi(libs.jdbiObject)
|
||||
compileOnlyApi(libs.jdbiPostgres)
|
||||
api(libs.hikariCP)
|
||||
api(libs.flyway)
|
||||
api(libs.flywayMysql)
|
||||
api(libs.caffeine)
|
||||
|
||||
// Messaging
|
||||
api(libs.messenger)
|
||||
api(libs.messengerNats)
|
||||
api(libs.messengerRabbitmq)
|
||||
api(libs.messengerRedis)
|
||||
api(libs.netty)
|
||||
api(libs.jedis)
|
||||
api(libs.rabbitmq)
|
||||
api(libs.nats)
|
||||
compileOnlyApi(libs.netty)
|
||||
|
||||
compileOnlyApi(libs.jarRelocator)
|
||||
compileOnlyApi(libs.caffeine)
|
||||
|
||||
// we shade and relocate a newer version than minecraft provides
|
||||
compileOnlyApi(libs.guava)
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
/*
|
||||
* CarbonChat
|
||||
*
|
||||
* Copyright (c) 2023 Josua Parks (Vicarious)
|
||||
* Contributors
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program 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 General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package net.draycia.carbon.common.util;
|
||||
|
||||
import com.google.common.hash.Hasher;
|
||||
import com.google.common.hash.Hashing;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.stream.Stream;
|
||||
import me.lucko.jarrelocator.JarRelocator;
|
||||
import me.lucko.jarrelocator.Relocation;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
public final class DependencyDownloader {
|
||||
|
||||
private final List<String> repositories = new ArrayList<>();
|
||||
private final List<Dependency> dependencies = new ArrayList<>();
|
||||
private final List<Relocation> relocations = new ArrayList<>();
|
||||
private final Logger logger;
|
||||
private final Path cacheDir;
|
||||
|
||||
public DependencyDownloader(
|
||||
final Logger logger,
|
||||
final Path cacheDir
|
||||
) {
|
||||
this.logger = logger;
|
||||
this.cacheDir = cacheDir;
|
||||
}
|
||||
|
||||
public Set<Path> resolve() {
|
||||
final Set<Path> ret = ConcurrentHashMap.newKeySet();
|
||||
final AtomicBoolean didWork = new AtomicBoolean(false);
|
||||
|
||||
final Runnable doingWork = () -> {
|
||||
if (didWork.compareAndSet(false, true)) {
|
||||
this.logger.info("Resolving dependencies...");
|
||||
}
|
||||
};
|
||||
|
||||
final List<Callable<Void>> tasks = this.dependencies.stream().map(dep -> (Callable<Void>) () -> {
|
||||
try {
|
||||
final Path resolve = this.resolve(dep, doingWork);
|
||||
if (!resolve.getFileName().toString().endsWith(".jar")) {
|
||||
return null;
|
||||
}
|
||||
if (this.relocations.isEmpty()) {
|
||||
ret.add(resolve);
|
||||
return null;
|
||||
}
|
||||
final Path output = resolve.resolveSibling(resolve.getFileName().toString().replace(".jar", "-relocated.jar"));
|
||||
ret.add(output);
|
||||
if (Files.isRegularFile(output)) {
|
||||
return null;
|
||||
}
|
||||
doingWork.run();
|
||||
final JarRelocator relocator = new JarRelocator(resolve.toFile(), output.toFile(), this.relocations);
|
||||
//this.logger.info("relocating {}", resolve);
|
||||
relocator.run();
|
||||
//this.logger.info("done relocating {}", resolve);
|
||||
} catch (final IOException e) {
|
||||
throw new RuntimeException("Exception resolving " + dep, e);
|
||||
}
|
||||
return null;
|
||||
}).toList();
|
||||
|
||||
this.executeTasks(tasks);
|
||||
|
||||
if (didWork.get()) {
|
||||
this.logger.info("Done resolving dependencies.");
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
private void executeTasks(final List<Callable<Void>> tasks) {
|
||||
final ExecutorService executor = this.makeExecutor();
|
||||
try {
|
||||
final List<Future<Void>> result = executor.invokeAll(tasks, 10, TimeUnit.MINUTES);
|
||||
@Nullable RuntimeException err = null;
|
||||
for (final Future<Void> f : result) {
|
||||
try {
|
||||
f.get();
|
||||
} catch (final ExecutionException | CancellationException e) {
|
||||
if (err == null) {
|
||||
err = new RuntimeException("Exception(s) resolving dependencies");
|
||||
}
|
||||
err.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
if (err != null) {
|
||||
throw err;
|
||||
}
|
||||
} catch (final InterruptedException e) {
|
||||
this.logger.error("Interrupted", e);
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
ConcurrentUtil.shutdownExecutor(executor, TimeUnit.MILLISECONDS, 2);
|
||||
}
|
||||
}
|
||||
|
||||
private Path resolve(final Dependency dependency, final Runnable attemptingDownloadCallback) throws IOException {
|
||||
final HttpClient client = HttpClient.newHttpClient();
|
||||
@Nullable Path resolved = null;
|
||||
final Path outputFile = this.cacheDir.resolve(String.format(
|
||||
"%s/%s/%s/%s-%s.jar",
|
||||
dependency.group.replace('.', '/'),
|
||||
dependency.name,
|
||||
dependency.version,
|
||||
dependency.name,
|
||||
dependency.version
|
||||
));
|
||||
if (Files.exists(outputFile)) {
|
||||
if (checkHash(dependency, outputFile)) {
|
||||
return outputFile;
|
||||
}
|
||||
Files.delete(outputFile);
|
||||
}
|
||||
attemptingDownloadCallback.run();
|
||||
for (final String repository : this.repositories) {
|
||||
final String urlString = String.format(
|
||||
"%s%s/%s/%s/%s-%s.jar",
|
||||
repository,
|
||||
dependency.group.replace('.', '/'),
|
||||
dependency.name,
|
||||
dependency.version,
|
||||
dependency.name,
|
||||
dependency.version
|
||||
);
|
||||
|
||||
final HttpRequest request;
|
||||
try {
|
||||
request = HttpRequest.newBuilder(new URI(urlString)).GET().build();
|
||||
} catch (final URISyntaxException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
final HttpResponse<Path> response;
|
||||
try {
|
||||
Files.createDirectories(outputFile.getParent());
|
||||
//this.logger.info("attempting to download " + urlString);
|
||||
response = client.send(request, HttpResponse.BodyHandlers.ofFile(
|
||||
outputFile,
|
||||
StandardOpenOption.TRUNCATE_EXISTING,
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.WRITE
|
||||
));
|
||||
} catch (final InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
if (response == null || response.statusCode() != 200) {
|
||||
//this.logger.info("Download " + urlString + " failed");
|
||||
continue;
|
||||
}
|
||||
//this.logger.info("Download " + urlString + " success");
|
||||
resolved = response.body();
|
||||
break;
|
||||
}
|
||||
if (resolved == null) {
|
||||
throw new IllegalStateException(String.format("Could not resolve dependency %s from any of %s", dependency, this.repositories));
|
||||
}
|
||||
if (!checkHash(dependency, resolved)) {
|
||||
throw new IllegalStateException("Hash for downloaded file %s was incorrect (expected: %s, got: %s)".formatted(resolved, dependency.sha256(), hashString(resolved)));
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private static boolean checkHash(final Dependency dependency, final Path resolved) throws IOException {
|
||||
return hashString(resolved).equalsIgnoreCase(dependency.sha256());
|
||||
}
|
||||
|
||||
private static String hashString(final Path resolved) throws IOException {
|
||||
final byte[] hash = com.google.common.io.Files.asByteSource(resolved.toFile()).hash(Hashing.sha256()).asBytes();
|
||||
return asHexString(hash);
|
||||
}
|
||||
|
||||
private static String asHexString(final byte[] bytes) {
|
||||
final StringBuilder sb = new StringBuilder(bytes.length * 2);
|
||||
for (final byte b : bytes) {
|
||||
sb.append("%02x".formatted(b & 0xFF));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private ExecutorService makeExecutor() {
|
||||
return Executors.newFixedThreadPool(
|
||||
Math.min(4, Runtime.getRuntime().availableProcessors()),
|
||||
ConcurrentUtil.carbonThreadFactory(this.logger, this.getClass().getSimpleName())
|
||||
);
|
||||
}
|
||||
|
||||
record Dependency(String group, String name, String version, String sha256) {}
|
||||
|
||||
public void load(final InputStream dependencyList) throws IOException {
|
||||
try (
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(dependencyList))
|
||||
) {
|
||||
boolean doneWithRepos = false;
|
||||
boolean doneWithDeps = false;
|
||||
final Hasher hasher = Hashing.sha256().newHasher();
|
||||
for (;;) {
|
||||
final String line = reader.readLine();
|
||||
if (line == null) {
|
||||
break;
|
||||
}
|
||||
if (line.equals("end_deps")) {
|
||||
doneWithDeps = true;
|
||||
continue;
|
||||
} else if (line.equals("end_repos")) {
|
||||
doneWithRepos = true;
|
||||
continue;
|
||||
}
|
||||
hasher.putUnencodedChars(line);
|
||||
if (doneWithDeps) {
|
||||
final String[] split = line.split(" ");
|
||||
this.relocations.add(new Relocation(split[0], split[1]));
|
||||
} else if (doneWithRepos) {
|
||||
final String[] split = line.split(" ");
|
||||
final String[] coords = split[0].split(":");
|
||||
this.dependencies.add(new Dependency(
|
||||
coords[0],
|
||||
coords[1],
|
||||
coords[2],
|
||||
split[1]
|
||||
));
|
||||
} else {
|
||||
this.repositories.add(line);
|
||||
}
|
||||
}
|
||||
final Path hashFile = this.cacheDir.resolve("input.hash");
|
||||
Files.createDirectories(this.cacheDir);
|
||||
final byte[] hash = hasher.hash().asBytes();
|
||||
if (Files.exists(hashFile)) {
|
||||
final byte[] existing = Files.readAllBytes(hashFile);
|
||||
if (!Arrays.equals(existing, hash)) {
|
||||
this.cleanCache();
|
||||
}
|
||||
} else {
|
||||
this.cleanCache();
|
||||
}
|
||||
Files.write(hashFile, hash);
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanCache() throws IOException {
|
||||
try (final Stream<Path> s = Files.walk(this.cacheDir)) {
|
||||
s.forEach(f -> {
|
||||
if (Files.isRegularFile(f) && f.getFileName().toString().endsWith(".jar")) {
|
||||
try {
|
||||
Files.delete(f);
|
||||
} catch (final IOException e) {
|
||||
Exceptions.rethrow(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+29
-13
@@ -37,29 +37,30 @@ dependencies {
|
||||
|
||||
modImplementation(libs.miniplaceholders)
|
||||
|
||||
include(libs.postgresql)
|
||||
runtimeOnly(libs.postgresql)
|
||||
include(libs.mysql)
|
||||
runtimeOnly(libs.mysql)
|
||||
include(libs.protobuf)
|
||||
runtimeOnly(libs.protobuf)
|
||||
include(libs.zstdjni)
|
||||
runtimeOnly(libs.zstdjni)
|
||||
runtimeDownload(libs.mysql)
|
||||
include(libs.jarRelocator)
|
||||
runtimeOnly(libs.jarRelocator) {
|
||||
isTransitive = false
|
||||
}
|
||||
runtimeDownload(libs.guice) {
|
||||
exclude("com.google.guava")
|
||||
}
|
||||
}
|
||||
|
||||
carbonPlatform {
|
||||
jarTask.set(tasks.remapJar)
|
||||
}
|
||||
|
||||
carbonShadowPlatform {
|
||||
relocateGuice.set(true)
|
||||
relocateCloud.set(false)
|
||||
}
|
||||
|
||||
tasks {
|
||||
shadowJar {
|
||||
configurations = arrayListOf(carbon) as List<FileCollection>
|
||||
relocateDependency("cloud.commandframework.minecraft.extras")
|
||||
standardRuntimeRelocations()
|
||||
relocateGuice()
|
||||
}
|
||||
writeDependencies {
|
||||
standardRuntimeRelocations()
|
||||
relocateGuice()
|
||||
}
|
||||
processResources {
|
||||
val props = mapOf(
|
||||
@@ -78,6 +79,21 @@ tasks {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
runServer {
|
||||
dependsOn(shadowJar)
|
||||
doFirst {
|
||||
val build = layout.buildDirectory.asFile.get().absolutePath
|
||||
val jar = shadowJar.get().archiveFile.get().asFile
|
||||
val mods = file("run/mods")
|
||||
mods.mkdirs()
|
||||
jar.copyTo(mods.resolve("carbonchat-dev.jar"), overwrite = true)
|
||||
val newClasspath = classpath.filter {
|
||||
!it.absolutePath.startsWith(build)
|
||||
}.files
|
||||
classpath = files(newClasspath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
modrinth {
|
||||
|
||||
@@ -20,17 +20,53 @@
|
||||
package net.draycia.carbon.fabric;
|
||||
|
||||
import com.google.inject.Guice;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import net.draycia.carbon.api.CarbonChatProvider;
|
||||
import net.draycia.carbon.common.util.DependencyDownloader;
|
||||
import net.fabricmc.api.ModInitializer;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import net.fabricmc.loader.launch.common.FabricLauncherBase;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
|
||||
public class CarbonFabricBootstrap implements ModInitializer {
|
||||
|
||||
@Override
|
||||
public void onInitialize() {
|
||||
this.loadDependencies();
|
||||
|
||||
final CarbonChatFabric carbonChat = Guice.createInjector(new CarbonChatFabricModule())
|
||||
.getInstance(CarbonChatFabric.class);
|
||||
CarbonChatProvider.register(carbonChat);
|
||||
carbonChat.onInitialize();
|
||||
}
|
||||
|
||||
private void loadDependencies() {
|
||||
final DependencyDownloader downloader = new DependencyDownloader(
|
||||
LogManager.getLogger(this.getClass().getSimpleName()),
|
||||
FabricLoader.getInstance().getConfigDir().resolve("carbonchat").resolve("libraries")
|
||||
);
|
||||
|
||||
try (final InputStream stream = Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream("carbon-dependencies.list"))) {
|
||||
downloader.load(stream);
|
||||
} catch (final IOException ex) {
|
||||
throw new RuntimeException("Couldn't load dependencies", ex);
|
||||
}
|
||||
|
||||
for (final Path dep : downloader.resolve()) {
|
||||
addJarToClasspath(dep);
|
||||
}
|
||||
}
|
||||
|
||||
private static void addJarToClasspath(final Path file) {
|
||||
try {
|
||||
FabricLauncherBase.getLauncher().propose(file.toUri().toURL());
|
||||
} catch (final MalformedURLException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -49,6 +49,7 @@ versions:
|
||||
protobuf: 3.21.9
|
||||
flyway: 8.5.13 # DO NOT UPDATE. Something will break.
|
||||
caffeine: 3.0.5
|
||||
mariadb: 3.0.8
|
||||
messenger: 1.0.0-SNAPSHOT
|
||||
netty: 4.1.68.Final
|
||||
zstdjni: 1.5.1-1
|
||||
@@ -238,6 +239,15 @@ dependencies:
|
||||
group: com.github.ben-manes.caffeine
|
||||
name: caffeine
|
||||
version: { ref: caffeine }
|
||||
mariadb:
|
||||
group: org.mariadb.jdbc
|
||||
name: mariadb-java-client
|
||||
version: { ref: mariadb }
|
||||
|
||||
jarRelocator:
|
||||
group: me.lucko
|
||||
name: jar-relocator
|
||||
version: 1.7
|
||||
|
||||
messenger:
|
||||
group: ninja.egg82
|
||||
|
||||
@@ -24,20 +24,23 @@ dependencies {
|
||||
compileOnly(libs.miniplaceholders)
|
||||
compileOnly(libs.essentialsXDiscord)
|
||||
compileOnly(libs.discordsrv)
|
||||
}
|
||||
|
||||
carbonShadowPlatform {
|
||||
relocateGuice.set(true)
|
||||
runtimeDownload(libs.guice) {
|
||||
exclude("com.google.guava")
|
||||
}
|
||||
}
|
||||
|
||||
tasks {
|
||||
shadowJar {
|
||||
relocateDependency("io.papermc.papertrail")
|
||||
relocateDependency("io.leangen.geantyref")
|
||||
relocateCloud()
|
||||
}
|
||||
runServer {
|
||||
minecraftVersion("1.20.1")
|
||||
}
|
||||
writeDependencies {
|
||||
}
|
||||
}
|
||||
|
||||
runPaper.folia.registerTask()
|
||||
|
||||
@@ -21,11 +21,15 @@ package net.draycia.carbon.paper;
|
||||
|
||||
import io.papermc.paper.plugin.loader.PluginClasspathBuilder;
|
||||
import io.papermc.paper.plugin.loader.PluginLoader;
|
||||
import io.papermc.paper.plugin.loader.library.impl.JarLibrary;
|
||||
import io.papermc.paper.plugin.loader.library.impl.MavenLibraryResolver;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import net.draycia.carbon.common.util.DependencyDownloader;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||
import org.eclipse.aether.artifact.DefaultArtifact;
|
||||
import org.eclipse.aether.graph.Dependency;
|
||||
import org.eclipse.aether.repository.RemoteRepository;
|
||||
import org.springframework.lang.NonNull;
|
||||
|
||||
@DefaultQualifier(NonNull.class)
|
||||
@@ -35,10 +39,23 @@ public class CarbonPaperLoader implements PluginLoader {
|
||||
public void classloader(final PluginClasspathBuilder classpathBuilder) {
|
||||
final MavenLibraryResolver maven = new MavenLibraryResolver();
|
||||
|
||||
maven.addRepository(new RemoteRepository.Builder("paper", "default", "https://repo.papermc.io/repository/maven-public/").build());
|
||||
final DependencyDownloader downloader;
|
||||
try (
|
||||
final InputStream stream = Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream("carbon-dependencies.list"))
|
||||
) {
|
||||
downloader = new DependencyDownloader(
|
||||
LogManager.getLogger(this.getClass().getSimpleName()),
|
||||
classpathBuilder.getContext().getDataDirectory().resolve("libraries")
|
||||
);
|
||||
|
||||
maven.addDependency(new Dependency(new DefaultArtifact("com.github.luben:zstd-jni:1.5.1-1"), null));
|
||||
maven.addDependency(new Dependency(new DefaultArtifact("org.postgresql:postgresql:42.3.1"), null));
|
||||
downloader.load(stream);
|
||||
} catch (final IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
for (final Path path : downloader.resolve()) {
|
||||
classpathBuilder.addLibrary(new JarLibrary(path));
|
||||
}
|
||||
|
||||
classpathBuilder.addLibrary(maven);
|
||||
}
|
||||
|
||||
+13
-18
@@ -15,28 +15,23 @@ dependencies {
|
||||
implementation(libs.cloudVelocity)
|
||||
compileOnly(libs.miniplaceholders)
|
||||
|
||||
runtimeOnly(libs.postgresql)
|
||||
runtimeOnly(libs.mysql)
|
||||
runtimeOnly(libs.zstdjni)
|
||||
runtimeOnly(libs.jarRelocator)
|
||||
|
||||
runtimeDownload(libs.mysql)
|
||||
}
|
||||
|
||||
tasks {
|
||||
shadowJar {
|
||||
dependencies {
|
||||
relocateDependency("io.leangen.geantyref")
|
||||
relocateDependency("com.google.inject.assistedinject")
|
||||
|
||||
relocateDependency("org.postgresql")
|
||||
relocateDependency("com.github.luben.zstd")
|
||||
relocateDependency("com.google.protobuf")
|
||||
relocateDependency("com.mysql.cj")
|
||||
relocateDependency("com.mysql.jdbc")
|
||||
|
||||
// included in velocity
|
||||
exclude(dependency("com.google.inject:guice"))
|
||||
exclude(dependency("aopalliance:aopalliance"))
|
||||
exclude(dependency("javax.inject:javax.inject"))
|
||||
}
|
||||
relocateCloud()
|
||||
standardRuntimeRelocations()
|
||||
relocateDependency("com.google.inject.assistedinject")
|
||||
relocateDependency("io.leangen.geantyref")
|
||||
relocateDependency("me.lucko.jarrelocator")
|
||||
relocateDependency("org.objectweb.asm")
|
||||
}
|
||||
writeDependencies {
|
||||
standardRuntimeRelocations()
|
||||
relocateDependency("com.google.inject.assistedinject")
|
||||
}
|
||||
runVelocity {
|
||||
velocityVersion(libs.versions.velocityApi.get())
|
||||
|
||||
@@ -29,7 +29,13 @@ import com.velocitypowered.api.plugin.Plugin;
|
||||
import com.velocitypowered.api.plugin.PluginContainer;
|
||||
import com.velocitypowered.api.plugin.annotation.DataDirectory;
|
||||
import com.velocitypowered.api.proxy.ProxyServer;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import net.draycia.carbon.common.util.DependencyDownloader;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
|
||||
|
||||
@Plugin(
|
||||
id = "$[ID]",
|
||||
@@ -46,7 +52,11 @@ import java.nio.file.Path;
|
||||
)
|
||||
public final class CarbonVelocityBootstrap {
|
||||
|
||||
private final CarbonChatVelocity carbonVelocity;
|
||||
private final Injector parentInjector;
|
||||
private final PluginContainer pluginContainer;
|
||||
private final ProxyServer proxy;
|
||||
private final Path dataDirectory;
|
||||
private @MonotonicNonNull Injector injector;
|
||||
|
||||
@Inject
|
||||
public CarbonVelocityBootstrap(
|
||||
@@ -55,18 +65,44 @@ public final class CarbonVelocityBootstrap {
|
||||
final PluginContainer pluginContainer,
|
||||
@DataDirectory final Path dataDirectory
|
||||
) {
|
||||
this.carbonVelocity = injector.createChildInjector(new CarbonChatVelocityModule(
|
||||
pluginContainer, proxyServer, dataDirectory)).getInstance(CarbonChatVelocity.class);
|
||||
this.proxy = proxyServer;
|
||||
this.parentInjector = injector;
|
||||
this.pluginContainer = pluginContainer;
|
||||
this.dataDirectory = dataDirectory;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onProxyInitialize(final ProxyInitializeEvent event) {
|
||||
this.carbonVelocity.onInitialization(this);
|
||||
this.loadDependencies(this.dataDirectory);
|
||||
this.injector = this.parentInjector.createChildInjector(
|
||||
new CarbonChatVelocityModule(this.pluginContainer, this.proxy, this.dataDirectory));
|
||||
this.injector.getInstance(CarbonChatVelocity.class).onInitialization(this);
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onProxyShutdown(final ProxyShutdownEvent event) {
|
||||
this.carbonVelocity.onShutdown();
|
||||
this.injector.getInstance(CarbonChatVelocity.class).onShutdown();
|
||||
}
|
||||
|
||||
private void loadDependencies(final Path dataDir) {
|
||||
final DependencyDownloader downloader = new DependencyDownloader(
|
||||
LogManager.getLogger(this.getClass().getSimpleName()),
|
||||
dataDir.resolve("libraries")
|
||||
);
|
||||
|
||||
try (final InputStream stream = Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream("carbon-dependencies.list"))) {
|
||||
downloader.load(stream);
|
||||
} catch (final IOException ex) {
|
||||
throw new RuntimeException("Couldn't load dependencies", ex);
|
||||
}
|
||||
|
||||
for (final Path dep : downloader.resolve()) {
|
||||
this.addJarToClasspath(dep);
|
||||
}
|
||||
}
|
||||
|
||||
private void addJarToClasspath(final Path file) {
|
||||
this.proxy.getPluginManager().addToClasspath(this, file);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user