|
18 | 18 | import java.util.jar.Manifest; |
19 | 19 | import java.util.zip.ZipEntry; |
20 | 20 | import java.util.zip.ZipInputStream; |
| 21 | + |
21 | 22 | import java.util.jar.Attributes.Name; |
| 23 | +import java.util.regex.Pattern; |
22 | 24 | import java.util.jar.JarFile; |
23 | 25 |
|
24 | 26 | class Util { |
@@ -262,4 +264,59 @@ private static List<Path> findAllClassPathEntries() { |
262 | 264 | return sneak(e); |
263 | 265 | } |
264 | 266 | } |
| 267 | + |
| 268 | + public static ModuleVersion findAutomaticModuleName(Path[] paths) { |
| 269 | + if (paths.length != 1 || paths[0].getFileName() == null) |
| 270 | + return null; |
| 271 | + |
| 272 | + var name = paths[0].getFileName().toString(); |
| 273 | + if (!name.endsWith(".jar")) |
| 274 | + return null; |
| 275 | + |
| 276 | + String version = null; |
| 277 | + var matcher = Patterns.DASH_VERSION.matcher(name); |
| 278 | + if (matcher.find()) { |
| 279 | + int start = matcher.start(); |
| 280 | + |
| 281 | + // attempt to parse the tail as a version string |
| 282 | + try { |
| 283 | + String tail = name.substring(start + 1); |
| 284 | + ModuleDescriptor.Version.parse(tail); |
| 285 | + version = tail; |
| 286 | + } catch (IllegalArgumentException ignore) { } |
| 287 | + |
| 288 | + name = name.substring(0, start); |
| 289 | + } |
| 290 | + |
| 291 | + return new ModuleVersion(cleanModuleName(name), version, null); |
| 292 | + } |
| 293 | + |
| 294 | + // Stolen from jdk.internal.module.ModulePath |
| 295 | + private static class Patterns { |
| 296 | + static final Pattern DASH_VERSION = Pattern.compile("-(\\d+(\\.|$))"); |
| 297 | + static final Pattern NON_ALPHANUM = Pattern.compile("[^A-Za-z0-9]"); |
| 298 | + static final Pattern REPEATING_DOTS = Pattern.compile("(\\.)(\\1)+"); |
| 299 | + static final Pattern LEADING_DOTS = Pattern.compile("^\\."); |
| 300 | + static final Pattern TRAILING_DOTS = Pattern.compile("\\.$"); |
| 301 | + } |
| 302 | + |
| 303 | + // Stolen from jdk.internal.module.ModulePath |
| 304 | + private static String cleanModuleName(String mn) { |
| 305 | + // replace non-alphanumeric |
| 306 | + mn = Patterns.NON_ALPHANUM.matcher(mn).replaceAll("."); |
| 307 | + |
| 308 | + // collapse repeating dots |
| 309 | + mn = Patterns.REPEATING_DOTS.matcher(mn).replaceAll("."); |
| 310 | + |
| 311 | + // drop leading dots |
| 312 | + if (!mn.isEmpty() && mn.charAt(0) == '.') |
| 313 | + mn = Patterns.LEADING_DOTS.matcher(mn).replaceAll(""); |
| 314 | + |
| 315 | + // drop trailing dots |
| 316 | + int len = mn.length(); |
| 317 | + if (len > 0 && mn.charAt(len-1) == '.') |
| 318 | + mn = Patterns.TRAILING_DOTS.matcher(mn).replaceAll(""); |
| 319 | + |
| 320 | + return mn; |
| 321 | + } |
265 | 322 | } |
0 commit comments