mirror of
https://github.com/darksaid98/Carbon.git
synced 2026-12-03 22:15:45 +00:00
Move dependency downloader code out of project
This commit is contained in:
1 parent
13c1e98872
commit
2ed9025101
13 files changed
+51
-517
No files matched your search
@@ -15,6 +15,7 @@ dependencies {
|
|||||||
implementation(libs.pluginYml)
|
implementation(libs.pluginYml)
|
||||||
implementation(libs.minotaur)
|
implementation(libs.minotaur)
|
||||||
implementation(libs.configurateYaml)
|
implementation(libs.configurateYaml)
|
||||||
|
implementation(libs.gremlin.gradle)
|
||||||
compileOnly("com.fasterxml.jackson.core:jackson-core:2.14.0")
|
compileOnly("com.fasterxml.jackson.core:jackson-core:2.14.0")
|
||||||
compileOnly("com.fasterxml.jackson.core:jackson-annotations:2.14.0")
|
compileOnly("com.fasterxml.jackson.core:jackson-annotations:2.14.0")
|
||||||
|
|
||||||
|
|||||||
@@ -1,109 +0,0 @@
|
|||||||
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
|
|
||||||
if (dependency.resolvedVariant.attributes.toString().contains("org.gradle.category=platform")) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
add(dependency)
|
|
||||||
if (transitive.get()) {
|
|
||||||
addFrom(dependency.selected.dependencies)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +1,12 @@
|
|||||||
plugins {
|
plugins {
|
||||||
id("carbon.base-conventions")
|
id("carbon.base-conventions")
|
||||||
id("com.modrinth.minotaur")
|
id("com.modrinth.minotaur")
|
||||||
|
id("xyz.jpenilla.gremlin-gradle")
|
||||||
}
|
}
|
||||||
|
|
||||||
decorateVersion()
|
decorateVersion()
|
||||||
|
|
||||||
val runtimeDownload: Configuration by configurations.creating {
|
configurations.runtimeDownload {
|
||||||
isCanBeResolved = true
|
|
||||||
isCanBeConsumed = false
|
|
||||||
attributes {
|
|
||||||
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME))
|
|
||||||
}
|
|
||||||
|
|
||||||
exclude("org.slf4j", "slf4j-api")
|
exclude("org.slf4j", "slf4j-api")
|
||||||
exclude("com.google.errorprone", "error_prone_annotations")
|
exclude("com.google.errorprone", "error_prone_annotations")
|
||||||
exclude("io.leangen.geantyref", "geantyref")
|
exclude("io.leangen.geantyref", "geantyref")
|
||||||
@@ -76,19 +71,15 @@ modrinth {
|
|||||||
gameVersions.addAll("1.19.4", "1.20.2")
|
gameVersions.addAll("1.19.4", "1.20.2")
|
||||||
}
|
}
|
||||||
|
|
||||||
val writeDeps = tasks.register("writeDependencies", WriteDependencies::class) {
|
tasks.writeDependencies {
|
||||||
tree.set(runtimeDownload.incoming.resolutionResult.rootComponent)
|
outputFileName.set("carbon-dependencies.txt")
|
||||||
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.papermc.io/repository/maven-public/")
|
||||||
repos.add("https://repo.maven.apache.org/maven2/")
|
repos.add("https://repo.maven.apache.org/maven2/")
|
||||||
}
|
}
|
||||||
|
|
||||||
sourceSets.main {
|
gremlin {
|
||||||
resources {
|
defaultJarRelocatorDependencies.set(false)
|
||||||
srcDir(writeDeps)
|
defaultGremlinRuntimeDependency.set(false)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//val projectVersion = version as String
|
//val projectVersion = version as String
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import org.gradle.api.provider.Provider
|
|||||||
import org.gradle.kotlin.dsl.filter
|
import org.gradle.kotlin.dsl.filter
|
||||||
import org.gradle.kotlin.dsl.the
|
import org.gradle.kotlin.dsl.the
|
||||||
import org.gradle.language.jvm.tasks.ProcessResources
|
import org.gradle.language.jvm.tasks.ProcessResources
|
||||||
|
import xyz.jpenilla.gremlin.gradle.ShadowGremlin
|
||||||
|
|
||||||
fun ProcessResources.replace(
|
fun ProcessResources.replace(
|
||||||
pattern: String,
|
pattern: String,
|
||||||
@@ -27,23 +28,11 @@ fun ProcessResources.replace(
|
|||||||
val Project.releaseNotes: Provider<String>
|
val Project.releaseNotes: Provider<String>
|
||||||
get() = providers.environmentVariable("RELEASE_NOTES")
|
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 `carbonchat.libs.` namespace.
|
* Relocate a package into the `carbonchat.libs.` namespace.
|
||||||
*/
|
*/
|
||||||
fun ShadowJar.relocateDependency(pkg: String) {
|
fun Task.relocateDependency(pkg: String) {
|
||||||
relocate(pkg, "carbonchat.libs.$pkg")
|
ShadowGremlin.relocate(this, pkg, "carbonchat.libs.$pkg")
|
||||||
}
|
|
||||||
|
|
||||||
fun WriteDependencies.relocateDependency(pkg: String) {
|
|
||||||
relocate(pkg, "carbonchat.libs.$pkg")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun Task.standardRuntimeRelocations() {
|
fun Task.standardRuntimeRelocations() {
|
||||||
@@ -81,6 +70,7 @@ fun Task.standardRelocations() {
|
|||||||
relocateDependency("ninja.egg82.messenger")
|
relocateDependency("ninja.egg82.messenger")
|
||||||
relocateDependency("org.antlr")
|
relocateDependency("org.antlr")
|
||||||
relocateDependency("com.electronwill")
|
relocateDependency("com.electronwill")
|
||||||
|
relocateDependency("xyz.jpenilla.gremlin")
|
||||||
}
|
}
|
||||||
|
|
||||||
fun Task.relocateCloud() {
|
fun Task.relocateCloud() {
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
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()
|
|
||||||
}
|
|
||||||
@@ -4,6 +4,7 @@ plugins {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
api(projects.carbonchatApi)
|
api(projects.carbonchatApi)
|
||||||
|
api(libs.gremlin.runtime)
|
||||||
compileOnlyApi(platform(libs.log4jBom))
|
compileOnlyApi(platform(libs.log4jBom))
|
||||||
compileOnlyApi(libs.log4jApi)
|
compileOnlyApi(libs.log4jApi)
|
||||||
|
|
||||||
@@ -58,7 +59,6 @@ dependencies {
|
|||||||
api(libs.kyoriMoonshineCore)
|
api(libs.kyoriMoonshineCore)
|
||||||
api(libs.kyoriMoonshineStandard)
|
api(libs.kyoriMoonshineStandard)
|
||||||
|
|
||||||
compileOnlyApi(libs.jarRelocator)
|
|
||||||
compileOnlyApi(libs.caffeine)
|
compileOnlyApi(libs.caffeine)
|
||||||
|
|
||||||
// we shade and relocate a newer version than minecraft provides
|
// we shade and relocate a newer version than minecraft provides
|
||||||
|
|||||||
@@ -19,14 +19,15 @@
|
|||||||
*/
|
*/
|
||||||
package net.draycia.carbon.common.util;
|
package net.draycia.carbon.common.util;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import org.apache.logging.log4j.LogManager;
|
|
||||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import xyz.jpenilla.gremlin.runtime.DependencyCache;
|
||||||
|
import xyz.jpenilla.gremlin.runtime.DependencyResolver;
|
||||||
|
import xyz.jpenilla.gremlin.runtime.DependencySet;
|
||||||
|
|
||||||
@DefaultQualifier(NonNull.class)
|
@DefaultQualifier(NonNull.class)
|
||||||
public final class CarbonDependencies {
|
public final class CarbonDependencies {
|
||||||
@@ -34,35 +35,17 @@ public final class CarbonDependencies {
|
|||||||
private CarbonDependencies() {
|
private CarbonDependencies() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void load(
|
public static Set<Path> resolve(final Path cacheDir) {
|
||||||
final Path cacheDir,
|
final DependencySet deps = DependencySet.readFromClasspathResource(
|
||||||
final Exceptions.CheckedConsumer<Path, Throwable> addToClasspath
|
CarbonDependencies.class.getClassLoader(), "carbon-dependencies.txt");
|
||||||
) {
|
final DependencyCache cache = new DependencyCache(cacheDir);
|
||||||
final DependencyDownloader downloader = new DependencyDownloader(
|
final Logger logger = LoggerFactory.getLogger(CarbonDependencies.class.getSimpleName());
|
||||||
LogManager.getLogger(CarbonDependencies.class.getSimpleName()),
|
final Set<Path> files;
|
||||||
cacheDir
|
try (final DependencyResolver downloader = new DependencyResolver(logger)) {
|
||||||
);
|
files = downloader.resolve(deps, cache).jarFiles();
|
||||||
|
|
||||||
try (final InputStream stream = Objects.requireNonNull(
|
|
||||||
CarbonDependencies.class.getClassLoader().getResourceAsStream("carbon-dependencies.list"),
|
|
||||||
"Could not get InputStream for carbon-dependencies.list"
|
|
||||||
)) {
|
|
||||||
downloader.load(stream);
|
|
||||||
} catch (final IOException ex) {
|
|
||||||
throw new RuntimeException("Failed to load dependency list", ex);
|
|
||||||
}
|
|
||||||
|
|
||||||
final Set<Path> resolved = downloader.resolve();
|
|
||||||
|
|
||||||
try {
|
|
||||||
for (final Path dep : resolved) {
|
|
||||||
addToClasspath.accept(dep);
|
|
||||||
}
|
|
||||||
} catch (final Error e) {
|
|
||||||
throw e;
|
|
||||||
} catch (final Throwable thr) {
|
|
||||||
throw new RuntimeException("Failed to add dependencies to classpath", thr);
|
|
||||||
}
|
}
|
||||||
|
cache.cleanup();
|
||||||
|
return files;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,289 +0,0 @@
|
|||||||
/*
|
|
||||||
* 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;
|
|
||||||
private final HttpClient client;
|
|
||||||
|
|
||||||
public DependencyDownloader(
|
|
||||||
final Logger logger,
|
|
||||||
final Path cacheDir
|
|
||||||
) {
|
|
||||||
this.logger = logger;
|
|
||||||
this.cacheDir = cacheDir;
|
|
||||||
this.client = HttpClient.newHttpClient();
|
|
||||||
}
|
|
||||||
|
|
||||||
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 relocated = resolve.resolveSibling(resolve.getFileName().toString().replace(".jar", "-relocated.jar"));
|
|
||||||
ret.add(relocated);
|
|
||||||
if (Files.isRegularFile(relocated)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
doingWork.run();
|
|
||||||
final Path output = relocated.resolveSibling(relocated.getFileName().toString() + ".tmp");
|
|
||||||
Files.deleteIfExists(output);
|
|
||||||
final JarRelocator relocator = new JarRelocator(resolve.toFile(), output.toFile(), this.relocations);
|
|
||||||
//this.logger.info("relocating {}", resolve);
|
|
||||||
relocator.run();
|
|
||||||
Files.move(output, relocated);
|
|
||||||
//this.logger.info("done relocating {}", resolve);
|
|
||||||
} catch (final IOException | IllegalArgumentException 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 {
|
|
||||||
@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 {
|
|
||||||
//this.logger.info("attempting to download " + urlString);
|
|
||||||
response = this.client.send(request, HttpResponse.BodyHandlers.ofFile(
|
|
||||||
FileUtil.mkParentDirs(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(), FileUtil.hashString(resolved)));
|
|
||||||
}
|
|
||||||
return resolved;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean checkHash(final Dependency dependency, final Path resolved) throws IOException {
|
|
||||||
return FileUtil.hashString(resolved).equalsIgnoreCase(dependency.sha256());
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -24,15 +24,16 @@ import net.draycia.carbon.api.CarbonChatProvider;
|
|||||||
import net.draycia.carbon.common.util.CarbonDependencies;
|
import net.draycia.carbon.common.util.CarbonDependencies;
|
||||||
import net.fabricmc.api.ModInitializer;
|
import net.fabricmc.api.ModInitializer;
|
||||||
import net.fabricmc.loader.api.FabricLoader;
|
import net.fabricmc.loader.api.FabricLoader;
|
||||||
import net.fabricmc.loader.launch.common.FabricLauncherBase;
|
import xyz.jpenilla.gremlin.runtime.platformsupport.FabricClasspathAppender;
|
||||||
|
|
||||||
public class CarbonFabricBootstrap implements ModInitializer {
|
public class CarbonFabricBootstrap implements ModInitializer {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onInitialize() {
|
public void onInitialize() {
|
||||||
CarbonDependencies.load(
|
new FabricClasspathAppender().append(
|
||||||
FabricLoader.getInstance().getConfigDir().resolve("carbonchat").resolve("libraries"),
|
CarbonDependencies.resolve(
|
||||||
path -> FabricLauncherBase.getLauncher().propose(path.toUri().toURL())
|
FabricLoader.getInstance().getConfigDir().resolve("carbonchat").resolve("libraries")
|
||||||
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
final CarbonChatFabric carbonChat = Guice.createInjector(new CarbonChatFabricModule())
|
final CarbonChatFabric carbonChat = Guice.createInjector(new CarbonChatFabricModule())
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ versions:
|
|||||||
pluginYml: 0.5.3
|
pluginYml: 0.5.3
|
||||||
minotaur: 2.7.5
|
minotaur: 2.7.5
|
||||||
h2: 2.2.224
|
h2: 2.2.224
|
||||||
|
gremlin: 0.0.2
|
||||||
|
|
||||||
dependencies:
|
dependencies:
|
||||||
adventureBom:
|
adventureBom:
|
||||||
@@ -345,6 +346,15 @@ dependencies:
|
|||||||
group: com.modrinth.minotaur
|
group: com.modrinth.minotaur
|
||||||
name: Minotaur
|
name: Minotaur
|
||||||
version: { ref: minotaur }
|
version: { ref: minotaur }
|
||||||
|
gremlin-gradle:
|
||||||
|
group: xyz.jpenilla
|
||||||
|
name: gremlin-gradle
|
||||||
|
version: { ref: gremlin }
|
||||||
|
|
||||||
|
gremlin-runtime:
|
||||||
|
group: xyz.jpenilla
|
||||||
|
name: gremlin-runtime
|
||||||
|
version: { ref: gremlin }
|
||||||
|
|
||||||
luckPermsApi:
|
luckPermsApi:
|
||||||
group: net.luckperms
|
group: net.luckperms
|
||||||
|
|||||||
@@ -21,19 +21,18 @@ package net.draycia.carbon.paper;
|
|||||||
|
|
||||||
import io.papermc.paper.plugin.loader.PluginClasspathBuilder;
|
import io.papermc.paper.plugin.loader.PluginClasspathBuilder;
|
||||||
import io.papermc.paper.plugin.loader.PluginLoader;
|
import io.papermc.paper.plugin.loader.PluginLoader;
|
||||||
import io.papermc.paper.plugin.loader.library.impl.JarLibrary;
|
|
||||||
import net.draycia.carbon.common.util.CarbonDependencies;
|
import net.draycia.carbon.common.util.CarbonDependencies;
|
||||||
import org.checkerframework.framework.qual.DefaultQualifier;
|
import org.checkerframework.framework.qual.DefaultQualifier;
|
||||||
import org.springframework.lang.NonNull;
|
import org.springframework.lang.NonNull;
|
||||||
|
import xyz.jpenilla.gremlin.runtime.platformsupport.PaperClasspathAppender;
|
||||||
|
|
||||||
@DefaultQualifier(NonNull.class)
|
@DefaultQualifier(NonNull.class)
|
||||||
public class CarbonPaperLoader implements PluginLoader {
|
public class CarbonPaperLoader implements PluginLoader {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void classloader(final PluginClasspathBuilder classpathBuilder) {
|
public void classloader(final PluginClasspathBuilder classpathBuilder) {
|
||||||
CarbonDependencies.load(
|
new PaperClasspathAppender(classpathBuilder).append(
|
||||||
classpathBuilder.getContext().getDataDirectory().resolve("libraries"),
|
CarbonDependencies.resolve(classpathBuilder.getContext().getDataDirectory().resolve("libraries"))
|
||||||
path -> classpathBuilder.addLibrary(new JarLibrary(path))
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,16 +12,11 @@ dependencies {
|
|||||||
implementation(libs.cloudVelocity)
|
implementation(libs.cloudVelocity)
|
||||||
compileOnly(libs.miniplaceholders)
|
compileOnly(libs.miniplaceholders)
|
||||||
|
|
||||||
runtimeOnly(libs.jarRelocator)
|
|
||||||
|
|
||||||
runtimeDownload(libs.mysql)
|
runtimeDownload(libs.mysql)
|
||||||
}
|
}
|
||||||
|
|
||||||
configurations.runtimeClasspath {
|
gremlin {
|
||||||
resolutionStrategy.force(
|
defaultJarRelocatorDependencies.set(true)
|
||||||
"org.ow2.asm:asm:9.6",
|
|
||||||
"org.ow2.asm:asm-commons:9.6",
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks {
|
tasks {
|
||||||
@@ -30,8 +25,6 @@ tasks {
|
|||||||
standardRuntimeRelocations()
|
standardRuntimeRelocations()
|
||||||
relocateDependency("com.google.inject.assistedinject")
|
relocateDependency("com.google.inject.assistedinject")
|
||||||
relocateDependency("io.leangen.geantyref")
|
relocateDependency("io.leangen.geantyref")
|
||||||
relocateDependency("me.lucko.jarrelocator")
|
|
||||||
relocateDependency("org.objectweb.asm")
|
|
||||||
}
|
}
|
||||||
writeDependencies {
|
writeDependencies {
|
||||||
standardRuntimeRelocations()
|
standardRuntimeRelocations()
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ import net.draycia.carbon.common.util.CarbonDependencies;
|
|||||||
import org.bstats.charts.SimplePie;
|
import org.bstats.charts.SimplePie;
|
||||||
import org.bstats.velocity.Metrics;
|
import org.bstats.velocity.Metrics;
|
||||||
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
|
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
|
||||||
|
import xyz.jpenilla.gremlin.runtime.platformsupport.VelocityClasspathAppender;
|
||||||
|
|
||||||
public final class CarbonVelocityBootstrap {
|
public final class CarbonVelocityBootstrap {
|
||||||
|
|
||||||
@@ -63,9 +64,8 @@ public final class CarbonVelocityBootstrap {
|
|||||||
|
|
||||||
@Subscribe
|
@Subscribe
|
||||||
public void onProxyInitialize(final ProxyInitializeEvent event) {
|
public void onProxyInitialize(final ProxyInitializeEvent event) {
|
||||||
CarbonDependencies.load(
|
new VelocityClasspathAppender(this.proxy, this).append(
|
||||||
this.dataDirectory.resolve("libraries"),
|
CarbonDependencies.resolve(this.dataDirectory.resolve("libraries"))
|
||||||
path -> this.proxy.getPluginManager().addToClasspath(this, path)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
this.injector = this.parentInjector.createChildInjector(
|
this.injector = this.parentInjector.createChildInjector(
|
||||||
|
|||||||
Reference in new issue
Block a user