Last active
April 21, 2021 18:20
-
-
Save bamboo/030ed98f1fb5c4853ac65455e67197dc to your computer and use it in GitHub Desktop.
Gradle ArtifactTransform example using the Gradle Kotlin DSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.gradle.api.internal.artifacts.repositories.layout.IvyRepositoryLayout | |
import java.io.InputStream | |
import java.util.zip.* | |
object Attributes { | |
val artifactType = Attribute.of("artifactType", String::class.java) | |
val zipType = "zip" | |
val jars = "jars" | |
} | |
/** | |
* Extracts all jars from a Gradle binary distribution. | |
*/ | |
class ExtractGradleJars : ArtifactTransform() { | |
override fun transform(input: File): List<File> { | |
unzipTo(outputDirectory, input) | |
return outputDirectory | |
.walkTopDown() | |
.filter { it.isFile && it.extension == "jar" } | |
.toList() | |
} | |
private | |
fun unzipTo(outputDirectory: File, zipFile: File) { | |
ZipFile(zipFile).use { zip -> | |
for (entry in zip.entries()) { | |
unzipEntryTo(outputDirectory, zip, entry) | |
} | |
} | |
} | |
private | |
fun unzipEntryTo(outputDirectory: File, zip: ZipFile, entry: ZipEntry) { | |
val output = File(outputDirectory, entry.name) | |
if (entry.isDirectory) { | |
output.mkdirs() | |
} else { | |
zip.getInputStream(entry).use { it.copyTo(output) } | |
} | |
} | |
private | |
fun InputStream.copyTo(file: File): Long = | |
file.outputStream().use { copyTo(it) } | |
} | |
val gradleDistribution by configurations.creating { | |
attributes { | |
attribute(Attributes.artifactType, Attributes.jars) | |
} | |
} | |
dependencies { | |
registerTransform { | |
from.attribute(Attributes.artifactType, Attributes.zipType) | |
to.attribute(Attributes.artifactType, Attributes.jars) | |
artifactTransform(ExtractGradleJars::class.java) | |
} | |
gradleDistribution( | |
group = "gradle", | |
name = "gradle", | |
version = "4.3.1", | |
configuration = null, | |
classifier = "bin", | |
ext = "zip") | |
} | |
repositories { | |
ivy { | |
name = "Gradle distributions" | |
url = uri("https://services.gradle.org/distributions") | |
layout("pattern") { | |
this as IvyPatternRepositoryLayout | |
artifact("[module]-[revision](-[classifier])(.[ext])") | |
} | |
} | |
} | |
tasks { | |
"printJarNames" { | |
doLast { | |
println(gradleDistribution.files.map { it.name }) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm glad you found the solution, @guai. Thanks for sharing it here!