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