| 1 |
import java.util.jar.JarEntry |
| 2 |
import java.util.jar.JarFile |
| 3 |
import java.util.jar.JarOutputStream |
| 4 |
import org.gradle.api.internal.file.archive.ZipCopyAction |
| 5 |
import java.nio.file.Files |
| 6 |
|
| 7 |
// This registers a `doLast` action to rewrite the timestamps of the project's output JAR |
| 8 |
afterEvaluate { |
| 9 |
val jarTask = (tasks.findByName("shadowJar") ?: tasks["jar"]) as Jar |
| 10 |
|
| 11 |
jarTask.doLast { |
| 12 |
|
| 13 |
val newFile = Files.createTempFile("rewrite-timestamp", null).toFile() |
| 14 |
val originalOutput = jarTask.archiveFile.get().asFile |
| 15 |
|
| 16 |
newFile.outputStream().use { os -> |
| 17 |
|
| 18 |
val newJarStream = JarOutputStream(os) |
| 19 |
val oldJar = JarFile(originalOutput) |
| 20 |
|
| 21 |
fun sortAlwaysFirst(name: String): Comparator<JarEntry> = |
| 22 |
Comparator { a, b -> |
| 23 |
when { |
| 24 |
a.name == name -> -1 |
| 25 |
b.name == name -> 1 |
| 26 |
else -> 0 |
| 27 |
} |
| 28 |
} |
| 29 |
|
| 30 |
oldJar.entries() |
| 31 |
.toList() |
| 32 |
.distinctBy { it.name } |
| 33 |
.sortedWith(sortAlwaysFirst("META-INF/") |
| 34 |
.then(sortAlwaysFirst("META-INF/MANIFEST.MF")) |
| 35 |
.thenBy { it.name }) |
| 36 |
.forEach { entry -> |
| 37 |
val jarEntry = JarEntry(entry.name) |
| 38 |
|
| 39 |
// Use the same constant as the fixed timestamps in normal copy actions |
| 40 |
jarEntry.time = ZipCopyAction.CONSTANT_TIME_FOR_ZIP_ENTRIES |
| 41 |
|
| 42 |
newJarStream.putNextEntry(jarEntry) |
| 43 |
|
| 44 |
oldJar.getInputStream(entry).copyTo(newJarStream) |
| 45 |
} |
| 46 |
|
| 47 |
newJarStream.finish() |
| 48 |
} |
| 49 |
|
| 50 |
newFile.renameTo(originalOutput) |
| 51 |
} |
| 52 |
} |