|
| 1 | +package org.mangorage.bootstrap; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.IOException; |
| 5 | +import java.lang.module.ModuleFinder; |
| 6 | +import java.nio.file.DirectoryStream; |
| 7 | +import java.nio.file.Files; |
| 8 | +import java.nio.file.Path; |
| 9 | +import java.nio.file.Paths; |
| 10 | +import java.nio.file.StandardCopyOption; |
| 11 | +import java.util.Comparator; |
| 12 | +import java.util.HashMap; |
| 13 | +import java.util.Map; |
| 14 | +import java.util.jar.JarFile; |
| 15 | +import java.util.zip.ZipEntry; |
| 16 | + |
| 17 | +public class LibraryHandler { |
| 18 | + |
| 19 | + public static void handle() throws IOException { |
| 20 | + Path source = Paths.get("libraries"); |
| 21 | + Path target = Paths.get("sortedLibraries"); |
| 22 | + |
| 23 | + if (Files.exists(target)) { |
| 24 | + deleteDirectory(target); |
| 25 | + } |
| 26 | + |
| 27 | + Files.createDirectories(target); |
| 28 | + |
| 29 | + Map<String, Path> seenModules = new HashMap<>(); |
| 30 | + |
| 31 | + try (DirectoryStream<Path> stream = Files.newDirectoryStream(source, "*.jar")) { |
| 32 | + for (Path jar : stream) { |
| 33 | + String moduleName = resolveModuleName(jar); |
| 34 | + if (moduleName == null) { |
| 35 | + System.out.println("Skipping non-module JAR: " + jar); |
| 36 | + continue; |
| 37 | + } |
| 38 | + |
| 39 | + if (!seenModules.containsKey(moduleName)) { |
| 40 | + Path dest = target.resolve(jar.getFileName()); |
| 41 | + Files.copy(jar, dest, StandardCopyOption.REPLACE_EXISTING); |
| 42 | + seenModules.put(moduleName, jar); |
| 43 | + System.out.println("Added module: " + moduleName); |
| 44 | + } else { |
| 45 | + System.out.println("Duplicate module ignored: " + moduleName + " from " + jar); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + System.out.println("Finished deduplicating modules. Result at: " + target); |
| 51 | + } |
| 52 | + |
| 53 | + private static void deleteDirectory(Path dir) throws IOException { |
| 54 | + Files.walk(dir) |
| 55 | + .sorted(Comparator.reverseOrder()) |
| 56 | + .map(Path::toFile) |
| 57 | + .forEach(File::delete); |
| 58 | + } |
| 59 | + |
| 60 | + private static String resolveModuleName(Path jarPath) { |
| 61 | + try (JarFile jarFile = new JarFile(jarPath.toFile())) { |
| 62 | + ZipEntry entry = jarFile.getEntry("module-info.class"); |
| 63 | + if (entry != null) { |
| 64 | + // This is a proper JPMS module JAR |
| 65 | + return ModuleFinder.of(jarPath).findAll().iterator().next().descriptor().name(); |
| 66 | + } else { |
| 67 | + // Fall back to heuristic based on filename (best effort) |
| 68 | + String filename = jarPath.getFileName().toString(); |
| 69 | + return filename.replaceAll("-[\\d\\.]+.*\\.jar$", "").replaceAll("\\.jar$", ""); |
| 70 | + } |
| 71 | + } catch (IOException e) { |
| 72 | + e.printStackTrace(); |
| 73 | + return null; |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments