Skip to content

Commit c54a1d1

Browse files
committed
refactor libraries
1 parent b8cc416 commit c54a1d1

File tree

18 files changed

+290
-146
lines changed

18 files changed

+290
-146
lines changed

build.gradle.kts

Lines changed: 7 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
import java.io.ByteArrayOutputStream
22

33
plugins {
4-
kotlin("jvm") version "1.6.10"
5-
kotlin("kapt") version "1.6.10"
6-
id("com.github.johnrengelman.shadow") version "7.0.0"
4+
kotlin("jvm") version "2.0.21"
5+
id("com.gradleup.shadow") version "8.3.3"
76
`maven-publish`
87
`java-library`
98
}
109

1110
group = "net.azisaba.spicyazisaban"
12-
version = "0.3.0-${getBranch()}-${getGitHash()}${if (hasUncommittedChanges()) "-debug" else ""}"
11+
version = "1.0.0-${getBranch()}-${getGitHash()}${if (hasUncommittedChanges()) "-debug" else ""}"
1312

1413
java {
1514
toolchain.languageVersion.set(JavaLanguageVersion.of(17))
@@ -33,7 +32,7 @@ fun getGitHash(): String {
3332
standardOutput = stdout
3433
}
3534
stdout.toString().trim()
36-
} catch (e: Exception) {
35+
} catch (_: Exception) {
3736
val ref = file("./.git/HEAD").readText().replace("^.*: (.*)$".toRegex(), "$1").trim(' ', '\n')
3837
println("Reading file ${file("./.git/$ref").absolutePath}")
3938
file("./.git/$ref").readText().trim(' ', '\n').substring(0..7)
@@ -48,7 +47,7 @@ fun hasUncommittedChanges(): Boolean {
4847
standardOutput = stdout
4948
}
5049
stdout.toString().trim().isNotBlank()
51-
} catch (e: Exception) {
50+
} catch (_: Exception) {
5251
false
5352
}
5453
}
@@ -78,8 +77,7 @@ subprojects {
7877

7978
apply {
8079
plugin("org.jetbrains.kotlin.jvm")
81-
plugin("org.jetbrains.kotlin.kapt")
82-
plugin("com.github.johnrengelman.shadow")
80+
plugin("com.gradleup.shadow")
8381
plugin("maven-publish")
8482
plugin("java-library")
8583
}
@@ -91,23 +89,12 @@ subprojects {
9189
}
9290

9391
tasks {
94-
compileKotlin {
95-
kotlinOptions.jvmTarget = "17"
96-
}
97-
98-
compileTestKotlin {
99-
kotlinOptions.jvmTarget = "17"
100-
}
101-
10292
test {
10393
useJUnitPlatform()
10494
}
10595

106-
kapt {
107-
this.javacOptions { this.option("source", 17) }
108-
}
109-
11096
processResources {
97+
doNotTrackState("bungee.yml should be updated every time")
11198
filteringCharset = "UTF-8"
11299
from(sourceSets.main.get().resources.srcDirs) {
113100
include("**")
@@ -121,18 +108,6 @@ subprojects {
121108

122109
filter<org.apache.tools.ant.filters.ReplaceTokens>("tokens" to tokenReplacementMap)
123110
}
124-
from(sourceSets.main.get().allSource.srcDirs) {
125-
include("**")
126-
127-
val tokenReplacementMap = mapOf(
128-
"version" to project.version,
129-
"name" to project.rootProject.name,
130-
"debugBuild" to hasUncommittedChanges().toString(),
131-
"devBuild" to (getBranch() != "main").toString(),
132-
)
133-
134-
filter<org.apache.tools.ant.filters.ReplaceTokens>("tokens" to tokenReplacementMap)
135-
}
136111

137112
duplicatesStrategy = DuplicatesStrategy.INCLUDE
138113

@@ -173,23 +148,6 @@ subprojects {
173148
}
174149

175150
dependencies {
176-
implementation("xyz.acrylicstyle.util:maven:0.16.6")
177-
implementation("net.blueberrymc:native-util:2.1.0")
178-
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.6.10")
179-
implementation("xyz.acrylicstyle.util:all:0.16.6") {
180-
exclude("com.google.guava", "guava")
181-
exclude("org.reflections", "reflections")
182-
exclude("org.json", "json")
183-
exclude("org.yaml", "snakeyaml")
184-
exclude("xyz.acrylicstyle.util", "maven")
185-
}
186-
implementation("xyz.acrylicstyle:sequelize4j:0.6.3") {
187-
exclude("xyz.acrylicstyle", "java-util-all")
188-
}
189-
implementation("xyz.acrylicstyle:minecraft-util:1.0.0") {
190-
exclude("xyz.acrylicstyle", "java-util-all")
191-
}
192-
compileOnly("org.mariadb.jdbc:mariadb-java-client:2.7.3")
193151
testImplementation("org.junit.jupiter:junit-jupiter:5.8.1")
194152
}
195153
}
@@ -221,10 +179,6 @@ allprojects {
221179
}
222180
}
223181

224-
println("Deleting cached bungee.yml")
225-
file("./build/resources/main/bungee.yml").apply {
226-
if (exists()) delete()
227-
}
228182
println("Version: ${project.version}")
229183
println("Debug build: ${hasUncommittedChanges()}")
230184
println("Dev build: ${project.version.toString().contains("-dev")}")

bungee/src/main/kotlin/net/azisaba/spicyAzisaBan/bungee/BungeePlugin.kt

Lines changed: 23 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ import net.azisaba.spicyAzisaBan.SpicyAzisaBan
55
import net.azisaba.spicyAzisaBan.bungee.listener.EventListeners
66
import net.azisaba.spicyAzisaBan.bungee.listener.LockdownListener
77
import net.azisaba.spicyAzisaBan.bungee.listener.PlayerDataUpdaterListener
8+
import net.azisaba.spicyAzisaBan.remapper.JarUtils
89
import net.blueberrymc.nativeutil.NativeUtil
910
import net.md_5.bungee.api.plugin.Plugin
10-
import util.maven.Dependency
11-
import util.maven.JarUtils
12-
import util.maven.MavenRepository
13-
import util.maven.Repository
11+
import org.eclipse.aether.util.graph.visitor.NodeListGenerator
12+
import org.eclipse.aether.util.graph.visitor.PreorderDependencyNodeConsumerVisitor
13+
import xyz.acrylicstyle.util.maven.MavenResolver
1414
import java.io.File
1515
import java.net.URLClassLoader
1616
import java.util.logging.Logger
@@ -23,36 +23,29 @@ class BungeePlugin: Plugin() {
2323
init {
2424
val dataFolder = File("plugins/SpicyAzisaBan")
2525
LOGGER.info("Data folder: ${dataFolder.absolutePath}")
26-
val maven = MavenRepository()
27-
maven.addRepository(Repository.mavenLocal())
28-
maven.addRepository(Repository.mavenCentral())
29-
maven.addDependency(Dependency.resolve('c' + "om.google.guava:guava:31.0.1-jre"))
30-
maven.addDependency(Dependency.resolve("org.reflections:reflections:0.10.2"))
31-
maven.addDependency(Dependency.resolve('o' + "rg.json:json:20210307"))
32-
maven.addDependency(Dependency.resolve("org.yaml:snakeyaml:1.29"))
33-
maven.addDependency(Dependency.resolve('o' + "rg.mariadb.jdbc:mariadb-java-client:2.7.3"))
34-
maven.addExclude("log4j", "log4j")
35-
var hasError = false
36-
val files = maven.newFetcher(File(dataFolder, "libraries")).withMessageReporter { msg, throwable ->
37-
if (throwable == null) {
38-
LOGGER.info(msg)
39-
} else {
40-
LOGGER.warning(msg)
26+
val nodeListGenerator = NodeListGenerator()
27+
MavenResolver("plugins/SpicyAzisaBan/libraries")
28+
.addMavenCentral()
29+
.addDependency('c' + "om.google.guava:guava:31.0.1-jre")
30+
.addDependency('o' + "rg.reflections:reflections:0.10.2")
31+
.addDependency('o' + "rg.json:json:20210307")
32+
.addDependency('o' + "rg.yaml:snakeyaml:1.29")
33+
.addDependency('o' + "rg.mariadb.jdbc:mariadb-java-client:3.5.0")
34+
.resolve { node, list -> node.artifact.groupId != "log4j" }
35+
.forEach {
36+
it.root.accept(PreorderDependencyNodeConsumerVisitor(nodeListGenerator))
4137
}
42-
throwable?.let {
43-
hasError = true
44-
it.printStackTrace()
45-
}
46-
}.downloadAllDependencies()
47-
if (hasError) LOGGER.warning("Failed to download some dependencies.")
48-
val cl = BungeePlugin::class.java.classLoader
49-
val urls = files.filterNotNull()
50-
.map { file -> JarUtils.remapJarWithClassPrefix(file, "-remapped", "net.azisaba.spicyAzisaBan.libs") }
51-
.map { file -> file.toURI().toURL() }
38+
val dedupe = nodeListGenerator.nodes.sortedByDescending { it.version }.distinctBy { it.artifact.groupId to it.artifact.artifactId }
39+
nodeListGenerator.nodes.retainAll(dedupe)
40+
val urls = nodeListGenerator.paths
41+
.map { it.toFile() }
42+
.map { JarUtils.remapJarWithClassPrefix(it, "-remapped", "net.azisaba.spicyAzisaBan.libs") }
43+
.map { it.toURI().toURL() }
5244
.toTypedArray()
45+
val cl = BungeePlugin::class.java.classLoader
5346
val libraryLoader = URLClassLoader(urls)
5447
NativeUtil.setObject(cl::class.java.getDeclaredField("libraryLoader"), cl, libraryLoader)
55-
LOGGER.info("Loaded libraries (" + files.size + "):")
48+
LOGGER.info("Loaded libraries (" + urls.size + "):")
5649
urls.forEach { url ->
5750
LOGGER.info(" - ${url.path}")
5851
}

cli/src/main/kotlin/net/azisaba/spicyAzisaBan/cli/actor/CLIActor.kt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import net.azisaba.spicyAzisaBan.common.PlayerActor
66
import net.azisaba.spicyAzisaBan.common.ServerInfo
77
import net.azisaba.spicyAzisaBan.common.chat.Component
88
import net.azisaba.spicyAzisaBan.common.title.Title
9-
import util.UUIDUtil
109
import java.net.SocketAddress
1110
import java.util.UUID
1211

@@ -26,7 +25,7 @@ object CLIActor: PlayerActor, Actor {
2625
override fun isOnline(): Boolean = true
2726

2827
override val name: String = "CONSOLE"
29-
override val uniqueId: UUID = UUIDUtil.NIL
28+
override val uniqueId: UUID = UUID(0, 0)
3029

3130
override fun sendMessage(component: Component) {
3231
println((component as SimpleComponent).getText())

common/build.gradle.kts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,22 @@
11
dependencies {
2-
api("xyz.acrylicstyle.java-util:common:1.0.0-SNAPSHOT")
2+
api("xyz.acrylicstyle.java-util:common:2.1.0")
3+
api("xyz.acrylicstyle.java-util:maven:2.1.0")
4+
api("net.blueberrymc:native-util:2.1.2")
5+
api("org.jetbrains.kotlin:kotlin-stdlib:2.0.21")
6+
api("xyz.acrylicstyle.util:all:0.16.6") {
7+
exclude("com.google.guava", "guava")
8+
exclude("org.reflections", "reflections")
9+
exclude("org.json", "json")
10+
exclude("org.yaml", "snakeyaml")
11+
exclude("xyz.acrylicstyle.util", "maven")
12+
}
13+
api("xyz.acrylicstyle:sequelize4j:0.6.3") {
14+
exclude("xyz.acrylicstyle", "java-util-all")
15+
}
16+
api("xyz.acrylicstyle:minecraft-util:1.0.0") {
17+
exclude("xyz.acrylicstyle", "java-util-all")
18+
}
19+
api("org.ow2.asm:asm:9.7.1")
20+
api("org.ow2.asm:asm-commons:9.7.1")
21+
compileOnlyApi("org.mariadb.jdbc:mariadb-java-client:3.5.0")
322
}
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
2+
package net.azisaba.spicyAzisaBan.remapper;
3+
4+
import com.google.common.io.ByteStreams;
5+
import org.jetbrains.annotations.NotNull;
6+
import org.objectweb.asm.ClassReader;
7+
import org.objectweb.asm.ClassWriter;
8+
import org.objectweb.asm.commons.ClassRemapper;
9+
import org.objectweb.asm.commons.Remapper;
10+
11+
import java.io.*;
12+
import java.util.ArrayList;
13+
import java.util.Enumeration;
14+
import java.util.List;
15+
import java.util.zip.ZipEntry;
16+
import java.util.zip.ZipFile;
17+
import java.util.zip.ZipOutputStream;
18+
19+
public class JarUtils {
20+
/**
21+
* Remap the class names.
22+
* @param src source jar (zip) file
23+
* @param fileSuffix suffix to apply to src file name.
24+
* @param prefix class name prefix without trailing dot or slash
25+
* @return destination file
26+
* @throws IOException if an I/O error occurs
27+
*/
28+
@NotNull
29+
public static File remapJarWithClassPrefix(@NotNull File src, @NotNull String fileSuffix, @NotNull String prefix) throws IOException {
30+
return remapJarWithClassPrefix(src, fileSuffix, prefix, new PrefixClassRemapper(prefix));
31+
}
32+
33+
/**
34+
* Remap the class names.
35+
* @param src source jar (zip) file
36+
* @param fileSuffix suffix to apply to src file name.
37+
* @param prefix class name prefix without trailing dot or slash
38+
* @return destination file
39+
* @throws IOException if an I/O error occurs
40+
*/
41+
@NotNull
42+
public static File remapJarWithClassPrefix(@NotNull File src, @NotNull String fileSuffix, @NotNull String prefix, @NotNull Remapper remapper) throws IOException {
43+
String[] split = src.getName().split("\\.");
44+
StringBuilder name = new StringBuilder(split[0]);
45+
for (int i = 1; i < split.length - 1; i++) name.append('.').append(split[i]);
46+
String extension = "";
47+
if (split.length > 1) extension = "." + split[split.length - 1];
48+
File dst = new File(src.getParentFile(), name + fileSuffix + extension);
49+
remapJarWithClassPrefix(src, dst, prefix, remapper);
50+
return dst;
51+
}
52+
53+
public static void remapJarWithClassPrefix(@NotNull File src, @NotNull File dst, @NotNull String prefix) throws IOException {
54+
remapJarWithClassPrefix(src, dst, prefix, new PrefixClassRemapper(prefix));
55+
}
56+
57+
public static void remapJarWithClassPrefix(@NotNull File src, @NotNull File dst, @NotNull String prefix, @NotNull Remapper remapper) throws IOException {
58+
ZipFile zipFile = new ZipFile(src);
59+
Enumeration<? extends ZipEntry> entries = zipFile.entries();
60+
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(dst));
61+
while (entries.hasMoreElements()) {
62+
ZipEntry entry = entries.nextElement();
63+
if (entry.getName().endsWith(".class")) {
64+
out.putNextEntry(new ZipEntry(prefix.replace('.', '/') + '/' + entry.getName()));
65+
byte[] bytes = remapClassWithClassPrefix(zipFile.getInputStream(entry), prefix, remapper);
66+
ByteStreams.copy(new ByteArrayInputStream(bytes), out);
67+
} else {
68+
out.putNextEntry(new ZipEntry(entry.getName()));
69+
if (entry.getName().equals("META-INF/MANIFEST.MF")) {
70+
StringBuilder sb = new StringBuilder();
71+
for (String line : readLines(zipFile.getInputStream(entry))) {
72+
if (line.startsWith("#")) {
73+
sb.append(line);
74+
} else {
75+
String[] split = line.split(": ");
76+
if (split.length == 1) {
77+
sb.append(split[0]);
78+
} else {
79+
sb.append(split[0]).append(": ");
80+
StringBuilder value = new StringBuilder();
81+
for (int i = 1; i < split.length; i++) value.append(split[i]);
82+
if (!split[0].equals("Import-Package") && line.matches("^\\D+\\..+")) {
83+
sb.append(remapper.map(value.toString()).replace('/', '.'));
84+
} else {
85+
sb.append(value);
86+
}
87+
}
88+
}
89+
sb.append("\n");
90+
}
91+
writeString(out, sb.toString());
92+
} else if (entry.getName().startsWith("META-INF/services/")) {
93+
StringBuilder sb = new StringBuilder();
94+
for (String line : readLines(zipFile.getInputStream(entry))) {
95+
if (line.startsWith("#")) {
96+
sb.append(line);
97+
} else if (line.matches("^\\D+\\..+")) { // if not blank:
98+
sb.append(remapper.map(line).replace('/', '.'));
99+
}
100+
sb.append("\n");
101+
}
102+
writeString(out, sb.toString());
103+
out.closeEntry();
104+
String service = entry.getName().replaceFirst("META-INF/services/(.*)", "$1");
105+
out.putNextEntry(new ZipEntry("META-INF/services/" + remapper.map(service).replace('/', '.')));
106+
writeString(out, sb.toString());
107+
} else {
108+
ByteStreams.copy(zipFile.getInputStream(entry), out);
109+
}
110+
}
111+
out.closeEntry();
112+
}
113+
zipFile.close();
114+
out.close();
115+
}
116+
117+
public static byte[] remapClassWithClassPrefix(@NotNull InputStream in, @NotNull String prefix, @NotNull Remapper remapper) throws IOException {
118+
ClassReader cr = new ClassReader(in);
119+
ClassWriter cw = new ClassWriter(0);
120+
cr.accept(new ClassRemapper(cw, remapper), 0);
121+
return cw.toByteArray();
122+
}
123+
124+
public static void writeString(@NotNull OutputStream out, @NotNull String s) throws IOException {
125+
OutputStreamWriter writer = new OutputStreamWriter(out);
126+
writer.write(s);
127+
writer.flush();
128+
}
129+
130+
@NotNull
131+
public static List<String> readLines(@NotNull InputStream in) throws IOException {
132+
try (InputStreamReader inputStreamReader = new InputStreamReader(in);
133+
BufferedReader reader = new BufferedReader(inputStreamReader)) {
134+
List<String> list = new ArrayList<>();
135+
String s;
136+
while ((s = reader.readLine()) != null) list.add(s);
137+
return list;
138+
}
139+
}
140+
}

0 commit comments

Comments
 (0)