|
| 1 | +import java.net.URI |
| 2 | +import java.nio.file.FileSystems |
| 3 | +import java.nio.file.Files |
| 4 | +import java.util.LinkedHashSet |
| 5 | +import java.util.zip.ZipFile |
| 6 | +import org.gradle.api.Action |
| 7 | +import org.gradle.api.Task |
| 8 | +import org.gradle.api.file.FileCollection |
| 9 | +import org.gradle.api.tasks.bundling.AbstractArchiveTask |
| 10 | + |
| 11 | +/** |
| 12 | + * Patches a built shadow JAR by merging Spring metadata and service descriptor files from the |
| 13 | + * runtime classpath into the final archive. |
| 14 | + * |
| 15 | + * Spring metadata files do not all share the same merge semantics, so this action merges |
| 16 | + * `spring.factories` as list properties, `.imports` files as line-based metadata, and other Spring |
| 17 | + * metadata as key/value properties. It also deduplicates service-provider configuration entries |
| 18 | + * under `META-INF/services` so the flat executable JAR keeps the runtime registrations it needs. |
| 19 | + */ |
| 20 | +class MergeSpringMetadataAction( |
| 21 | + private val runtimeClasspath: FileCollection, |
| 22 | + private val springMetadataFiles: List<String>, |
| 23 | +) : Action<Task> { |
| 24 | + companion object { |
| 25 | + val DEFAULT_SPRING_METADATA_FILES = |
| 26 | + listOf( |
| 27 | + "META-INF/spring.factories", |
| 28 | + "META-INF/spring.handlers", |
| 29 | + "META-INF/spring.schemas", |
| 30 | + "META-INF/spring-autoconfigure-metadata.properties", |
| 31 | + "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports", |
| 32 | + "META-INF/spring/org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration.imports", |
| 33 | + ) |
| 34 | + } |
| 35 | + |
| 36 | + override fun execute(task: Task) { |
| 37 | + val archiveTask = task as AbstractArchiveTask |
| 38 | + val jar = archiveTask.archiveFile.get().asFile |
| 39 | + val runtimeJars = runtimeClasspath.files.filter { it.name.endsWith(".jar") } |
| 40 | + val uri = URI.create("jar:${jar.toURI()}") |
| 41 | + |
| 42 | + FileSystems.newFileSystem(uri, mapOf("create" to "false")).use { fs -> |
| 43 | + springMetadataFiles.forEach { entryPath -> |
| 44 | + val target = fs.getPath(entryPath) |
| 45 | + val contents = mutableListOf<String>() |
| 46 | + |
| 47 | + if (Files.exists(target)) { |
| 48 | + contents.add(Files.readString(target)) |
| 49 | + } |
| 50 | + |
| 51 | + runtimeJars.forEach { depJar -> |
| 52 | + try { |
| 53 | + ZipFile(depJar).use { zip -> |
| 54 | + val entry = zip.getEntry(entryPath) |
| 55 | + if (entry != null) { |
| 56 | + contents.add(zip.getInputStream(entry).bufferedReader().readText()) |
| 57 | + } |
| 58 | + } |
| 59 | + } catch (_: Exception) { |
| 60 | + // Ignore non-zip files on the runtime classpath. |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + val merged = |
| 65 | + when { |
| 66 | + entryPath == "META-INF/spring.factories" -> mergeListProperties(contents) |
| 67 | + entryPath.endsWith(".imports") -> mergeLineBasedMetadata(contents) |
| 68 | + else -> mergeMapProperties(contents) |
| 69 | + } |
| 70 | + |
| 71 | + if (merged.isNotEmpty()) { |
| 72 | + if (target.parent != null) { |
| 73 | + Files.createDirectories(target.parent) |
| 74 | + } |
| 75 | + Files.write(target, merged.toByteArray()) |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + val serviceEntries = linkedSetOf<String>() |
| 80 | + |
| 81 | + runtimeJars.forEach { depJar -> |
| 82 | + try { |
| 83 | + ZipFile(depJar).use { zip -> |
| 84 | + val entries = zip.entries() |
| 85 | + while (entries.hasMoreElements()) { |
| 86 | + val entry = entries.nextElement() |
| 87 | + if (!entry.isDirectory && entry.name.startsWith("META-INF/services/")) { |
| 88 | + serviceEntries.add(entry.name) |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + } catch (_: Exception) { |
| 93 | + // Ignore non-zip files on the runtime classpath. |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + serviceEntries.forEach { entryPath -> |
| 98 | + val providers = LinkedHashSet<String>() |
| 99 | + val target = fs.getPath(entryPath) |
| 100 | + |
| 101 | + if (Files.exists(target)) { |
| 102 | + Files.newBufferedReader(target).useLines { lines -> |
| 103 | + lines.forEach { line -> |
| 104 | + val provider = line.trim() |
| 105 | + if (provider.isNotEmpty() && !provider.startsWith("#")) { |
| 106 | + providers.add(provider) |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + runtimeJars.forEach { depJar -> |
| 113 | + try { |
| 114 | + ZipFile(depJar).use { zip -> |
| 115 | + val entry = zip.getEntry(entryPath) |
| 116 | + if (entry != null) { |
| 117 | + zip.getInputStream(entry).bufferedReader().useLines { lines -> |
| 118 | + lines.forEach { line -> |
| 119 | + val provider = line.trim() |
| 120 | + if (provider.isNotEmpty() && !provider.startsWith("#")) { |
| 121 | + providers.add(provider) |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + } catch (_: Exception) { |
| 128 | + // Ignore non-zip files on the runtime classpath. |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + if (providers.isNotEmpty()) { |
| 133 | + if (target.parent != null) { |
| 134 | + Files.createDirectories(target.parent) |
| 135 | + } |
| 136 | + Files.write(target, providers.joinToString(separator = "\n", postfix = "\n").toByteArray()) |
| 137 | + } |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + private fun mergeLineBasedMetadata(contents: List<String>): String { |
| 143 | + val lines = LinkedHashSet<String>() |
| 144 | + |
| 145 | + contents.forEach { content -> |
| 146 | + content.lineSequence().forEach { rawLine -> |
| 147 | + val line = rawLine.trim() |
| 148 | + if (line.isNotEmpty() && !line.startsWith("#")) { |
| 149 | + lines.add(line) |
| 150 | + } |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + return if (lines.isEmpty()) "" else lines.joinToString(separator = "\n", postfix = "\n") |
| 155 | + } |
| 156 | + |
| 157 | + private fun mergeMapProperties(contents: List<String>): String { |
| 158 | + val merged = linkedMapOf<String, String>() |
| 159 | + |
| 160 | + contents.forEach { content -> |
| 161 | + parseProperties(content).forEach { (key, value) -> |
| 162 | + merged[key] = value |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + return if (merged.isEmpty()) { |
| 167 | + "" |
| 168 | + } else { |
| 169 | + merged.entries.joinToString(separator = "\n", postfix = "\n") { (key, value) -> "$key=$value" } |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + private fun mergeListProperties(contents: List<String>): String { |
| 174 | + val merged = linkedMapOf<String, LinkedHashSet<String>>() |
| 175 | + |
| 176 | + contents.forEach { content -> |
| 177 | + parseProperties(content).forEach { (key, value) -> |
| 178 | + val values = merged.getOrPut(key) { LinkedHashSet() } |
| 179 | + value |
| 180 | + .split(',') |
| 181 | + .map(String::trim) |
| 182 | + .filter(String::isNotEmpty) |
| 183 | + .forEach(values::add) |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + return if (merged.isEmpty()) { |
| 188 | + "" |
| 189 | + } else { |
| 190 | + merged.entries.joinToString(separator = "\n", postfix = "\n") { (key, values) -> |
| 191 | + "$key=${values.joinToString(separator = ",")}" |
| 192 | + } |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + private fun parseProperties(content: String): List<Pair<String, String>> { |
| 197 | + val logicalLines = mutableListOf<String>() |
| 198 | + val current = StringBuilder() |
| 199 | + |
| 200 | + content.lineSequence().forEach { rawLine -> |
| 201 | + val line = rawLine.trim() |
| 202 | + if (current.isEmpty() && (line.isEmpty() || line.startsWith("#") || line.startsWith("!"))) { |
| 203 | + return@forEach |
| 204 | + } |
| 205 | + |
| 206 | + val normalized = if (current.isEmpty()) line else line.trimStart() |
| 207 | + current.append( |
| 208 | + if (endsWithContinuation(rawLine)) normalized.dropLast(1) else normalized, |
| 209 | + ) |
| 210 | + |
| 211 | + if (!endsWithContinuation(rawLine)) { |
| 212 | + logicalLines.add(current.toString()) |
| 213 | + current.setLength(0) |
| 214 | + } |
| 215 | + } |
| 216 | + |
| 217 | + if (current.isNotEmpty()) { |
| 218 | + logicalLines.add(current.toString()) |
| 219 | + } |
| 220 | + |
| 221 | + return logicalLines.map { line -> |
| 222 | + val separatorIndex = findSeparatorIndex(line) |
| 223 | + if (separatorIndex < 0) { |
| 224 | + line to "" |
| 225 | + } else { |
| 226 | + val keyEnd = trimTrailingWhitespace(line, separatorIndex) |
| 227 | + val valueStart = findValueStart(line, separatorIndex) |
| 228 | + line.substring(0, keyEnd) to line.substring(valueStart).trim() |
| 229 | + } |
| 230 | + } |
| 231 | + } |
| 232 | + |
| 233 | + private fun endsWithContinuation(line: String): Boolean { |
| 234 | + var backslashCount = 0 |
| 235 | + |
| 236 | + for (index in line.length - 1 downTo 0) { |
| 237 | + if (line[index] == '\\') { |
| 238 | + backslashCount++ |
| 239 | + } else { |
| 240 | + break |
| 241 | + } |
| 242 | + } |
| 243 | + |
| 244 | + return backslashCount % 2 == 1 |
| 245 | + } |
| 246 | + |
| 247 | + private fun findSeparatorIndex(line: String): Int { |
| 248 | + var backslashCount = 0 |
| 249 | + |
| 250 | + line.forEachIndexed { index, char -> |
| 251 | + if (char == '\\') { |
| 252 | + backslashCount++ |
| 253 | + } else { |
| 254 | + val isEscaped = backslashCount % 2 == 1 |
| 255 | + if (!isEscaped && (char == '=' || char == ':' || char.isWhitespace())) { |
| 256 | + return index |
| 257 | + } |
| 258 | + backslashCount = 0 |
| 259 | + } |
| 260 | + } |
| 261 | + |
| 262 | + return -1 |
| 263 | + } |
| 264 | + |
| 265 | + private fun trimTrailingWhitespace(line: String, endExclusive: Int): Int { |
| 266 | + var end = endExclusive |
| 267 | + |
| 268 | + while (end > 0 && line[end - 1].isWhitespace()) { |
| 269 | + end-- |
| 270 | + } |
| 271 | + |
| 272 | + return end |
| 273 | + } |
| 274 | + |
| 275 | + private fun findValueStart(line: String, separatorIndex: Int): Int { |
| 276 | + var valueStart = separatorIndex |
| 277 | + |
| 278 | + while (valueStart < line.length && line[valueStart].isWhitespace()) { |
| 279 | + valueStart++ |
| 280 | + } |
| 281 | + |
| 282 | + if (valueStart < line.length && (line[valueStart] == '=' || line[valueStart] == ':')) { |
| 283 | + valueStart++ |
| 284 | + } |
| 285 | + |
| 286 | + while (valueStart < line.length && line[valueStart].isWhitespace()) { |
| 287 | + valueStart++ |
| 288 | + } |
| 289 | + |
| 290 | + return valueStart |
| 291 | + } |
| 292 | +} |
0 commit comments