|
| 1 | +package projections.spring; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.IOException; |
| 5 | +import java.nio.charset.StandardCharsets; |
| 6 | +import java.nio.file.Files; |
| 7 | +import java.nio.file.Path; |
| 8 | +import java.util.ArrayList; |
| 9 | +import java.util.Comparator; |
| 10 | +import java.util.LinkedHashSet; |
| 11 | +import java.util.List; |
| 12 | +import java.util.Map; |
| 13 | +import java.util.Set; |
| 14 | +import java.util.TreeMap; |
| 15 | +import java.util.regex.Matcher; |
| 16 | +import java.util.regex.Pattern; |
| 17 | + |
| 18 | +/** |
| 19 | + * Names the files on the runtime classpath without where the build or the user's caches put them, because that |
| 20 | + * differs between machines and runs. A file in a classpath directory is named relative to it |
| 21 | + * ({@code file [/repo/target/classes/messages.properties]} is {@code file [messages.properties]}) and a jar by its file |
| 22 | + * name ({@code URL [jar:file:/home/me/.m2/repository/…/common.jar!/messages.properties]} is |
| 23 | + * {@code URL [jar:common.jar!/messages.properties]}). |
| 24 | + */ |
| 25 | +final class ClasspathNames { |
| 26 | + /** Each way a message can spell a classpath entry, longest first so a nested entry is replaced whole, and its replacement. */ |
| 27 | + private final List<Map.Entry<Pattern, String>> replacements; |
| 28 | + |
| 29 | + private ClasspathNames(List<Map.Entry<Pattern, String>> replacements) { |
| 30 | + this.replacements = replacements; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * The entries of {@code java.class.path}: the application's class and resource directories, and the jars or |
| 35 | + * directories of its build's other modules (Gradle subprojects, Maven modules) and of its dependencies. |
| 36 | + */ |
| 37 | + static ClasspathNames ofRuntime() { |
| 38 | + List<Path> entries = new ArrayList<>(); |
| 39 | + for (String entry : System.getProperty("java.class.path", "").split(File.pathSeparator)) { |
| 40 | + try { |
| 41 | + if (!entry.isEmpty()) entries.add(Path.of(entry)); |
| 42 | + } catch (RuntimeException ignored) { |
| 43 | + // An entry that is not a path names no file. |
| 44 | + } |
| 45 | + } |
| 46 | + return of(entries); |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Each directory and file is spelled as given and as resolved, with native and URL separators, and as a URL path |
| 51 | + * ({@code /C:/…} on Windows); a jar also inside a {@code jar:file:} URL. A spelling also matches with any of its |
| 52 | + * characters percent-encoded, in either case, because encoders differ: the class loader's resource URLs spell |
| 53 | + * {@code a=b[1]} as {@code a%3db%5b1%5d}, and {@link File#toURI()} and {@link Path#toUri()} as {@code a=b%5B1%5D}. |
| 54 | + */ |
| 55 | + static ClasspathNames of(List<Path> entries) { |
| 56 | + Map<String, String> replacements = new TreeMap<>(Comparator.comparingInt(String::length).reversed().thenComparing(Comparator.naturalOrder())); |
| 57 | + for (Path entry : entries) { |
| 58 | + boolean directory = Files.isDirectory(entry); |
| 59 | + if (!directory && !Files.isRegularFile(entry)) continue; |
| 60 | + String name = directory ? "" : entry.getFileName().toString(); |
| 61 | + for (Path spelling : spellings(entry)) { |
| 62 | + // The filesystem root is a prefix of every path, not where the build put anything. |
| 63 | + if (spelling.getParent() == null) continue; |
| 64 | + String text = spelling.toString(); |
| 65 | + String url = urlPath(spelling); |
| 66 | + if (directory) { |
| 67 | + replacements.put(text + File.separator, ""); |
| 68 | + replacements.put(text.replace(File.separatorChar, '/') + "/", ""); |
| 69 | + if (url != null) replacements.put(url.endsWith("/") ? url : url + "/", ""); |
| 70 | + } else { |
| 71 | + replacements.put(text, name); |
| 72 | + replacements.put(text.replace(File.separatorChar, '/'), name); |
| 73 | + if (url != null) { |
| 74 | + replacements.put(url, name); |
| 75 | + replacements.put("jar:file:" + url + "!/", "jar:" + name + "!/"); |
| 76 | + replacements.put("jar:file://" + url + "!/", "jar:" + name + "!/"); |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + List<Map.Entry<Pattern, String>> patterns = new ArrayList<>(); |
| 82 | + for (Map.Entry<String, String> replacement : replacements.entrySet()) { |
| 83 | + patterns.add(Map.entry(anyEncoding(replacement.getKey()), Matcher.quoteReplacement(replacement.getValue()))); |
| 84 | + } |
| 85 | + return new ClasspathNames(List.copyOf(patterns)); |
| 86 | + } |
| 87 | + |
| 88 | + String apply(String message) { |
| 89 | + // A message without a separator names no path, and most condition messages name only classes and properties. |
| 90 | + if (message.indexOf('/') < 0 && message.indexOf(File.separatorChar) < 0) return message; |
| 91 | + String result = message; |
| 92 | + for (Map.Entry<Pattern, String> replacement : replacements) { |
| 93 | + result = replacement.getKey().matcher(result).replaceAll(replacement.getValue()); |
| 94 | + } |
| 95 | + return result; |
| 96 | + } |
| 97 | + |
| 98 | + /** The entry as given (made absolute) and as resolved, which differ through a symbolic link such as macOS's /tmp. */ |
| 99 | + private static List<Path> spellings(Path entry) { |
| 100 | + Set<Path> spellings = new LinkedHashSet<>(List.of(entry.toAbsolutePath().normalize())); |
| 101 | + try { |
| 102 | + spellings.add(entry.toRealPath()); |
| 103 | + } catch (IOException | RuntimeException ignored) { |
| 104 | + // An entry that cannot be resolved is only spelled as given. |
| 105 | + } |
| 106 | + return List.copyOf(spellings); |
| 107 | + } |
| 108 | + |
| 109 | + /** The path as a {@code file:} URL names it, decoded; it starts with {@code /}, also on Windows. */ |
| 110 | + private static String urlPath(Path path) { |
| 111 | + try { |
| 112 | + String url = path.toFile().toURI().getPath(); |
| 113 | + return url == null || url.isEmpty() || "/".equals(url) ? null : url; |
| 114 | + } catch (RuntimeException ignored) { |
| 115 | + // A path without a URL spelling is only spelled natively. |
| 116 | + return null; |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + /** Matches {@code text} with any character but a letter, digit or {@code /} also percent-encoded as UTF-8, in either case. */ |
| 121 | + static Pattern anyEncoding(String text) { |
| 122 | + StringBuilder pattern = new StringBuilder(); |
| 123 | + text.codePoints().forEach(codePoint -> { |
| 124 | + String character = Character.toString(codePoint); |
| 125 | + if (codePoint < 0x80 && (Character.isLetterOrDigit(codePoint) || codePoint == '/')) { |
| 126 | + pattern.append(character); |
| 127 | + return; |
| 128 | + } |
| 129 | + pattern.append("(?:").append(Pattern.quote(character)); |
| 130 | + pattern.append('|'); |
| 131 | + for (byte value : character.getBytes(StandardCharsets.UTF_8)) { |
| 132 | + pattern.append('%').append(hexDigit((value >> 4) & 0xF)).append(hexDigit(value & 0xF)); |
| 133 | + } |
| 134 | + pattern.append(')'); |
| 135 | + }); |
| 136 | + return Pattern.compile(pattern.toString()); |
| 137 | + } |
| 138 | + |
| 139 | + private static String hexDigit(int value) { |
| 140 | + char digit = Character.forDigit(value, 16); |
| 141 | + return Character.isLetter(digit) ? "[" + digit + Character.toUpperCase(digit) + "]" : String.valueOf(digit); |
| 142 | + } |
| 143 | +} |
0 commit comments