Fix manifest util for bundler jars

This commit is contained in:
Jason Penilla 2021-11-26 17:03:47 -08:00
parent 01afd3826e
commit a16b294eee

View file

@ -14,14 +14,13 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Collections;
+import java.util.Map;
+import java.util.WeakHashMap;
+import java.util.jar.Manifest;
+
+import org.jetbrains.annotations.ApiStatus;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+@ApiStatus.Internal
+public final class JarManifests {
@ -30,16 +29,19 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000
+
+ private static final Map<ClassLoader, Manifest> MANIFESTS = Collections.synchronizedMap(new WeakHashMap<>());
+
+ public static @NotNull Manifest manifest(final @NotNull ClassLoader loader) {
+ return MANIFESTS.computeIfAbsent(loader, classLoader -> {
+ final @Nullable InputStream stream = classLoader.getResourceAsStream("META-INF/MANIFEST.MF");
+ if (stream == null) {
+ throw new IllegalArgumentException("Provided ClassLoader does not have a manifest file in the correct location!");
+ public static @NotNull Manifest manifest(final @NotNull Class<?> clazz) {
+ return MANIFESTS.computeIfAbsent(clazz.getClassLoader(), classLoader -> {
+ final String classLocation = "/" + clazz.getName().replace(".", "/") + ".class";
+ final URL resource = clazz.getResource(classLocation);
+ if (resource == null) {
+ throw new IllegalStateException("Could not find class file for loaded class: " + clazz.getName());
+ }
+ try (stream) {
+ final String classFilePath = resource.toString().replace("\\", "/");
+ final String archivePath = classFilePath.substring(0, classFilePath.length() - classLocation.length());
+ try (final InputStream stream = new URL(archivePath + "/META-INF/MANIFEST.MF").openStream()) {
+ return new Manifest(stream);
+ } catch (final IOException ex) {
+ throw new RuntimeException("Failed to read manifest.");
+ throw new RuntimeException("Failed to locate or read manifest", ex);
+ }
+ });
+ }
@ -71,7 +73,7 @@ index 0000000000000000000000000000000000000000..00000000000000000000000000000000
+ */
+ @NotNull
+ public static String getVersionMessage() {
+ final var manifest = JarManifests.manifest(Bukkit.getServer().getClass().getClassLoader());
+ final var manifest = JarManifests.manifest(Bukkit.getServer().getClass());
+ final String gitBranch = manifest.getMainAttributes().getValue("Git-Branch");
+ final String gitCommit = manifest.getMainAttributes().getValue("Git-Commit");
+ String branchMsg = " on " + gitBranch;