Skip to content

Instantly share code, notes, and snippets.

@bamboo
Last active April 21, 2021 18:20
Show Gist options
  • Save bamboo/030ed98f1fb5c4853ac65455e67197dc to your computer and use it in GitHub Desktop.
Save bamboo/030ed98f1fb5c4853ac65455e67197dc to your computer and use it in GitHub Desktop.
Gradle ArtifactTransform example using the Gradle Kotlin DSL
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 })
}
}
}
@guai
Copy link

guai commented Apr 21, 2021

Nevermind. One must add ivy { metadataSources.artifact() } in order to make the code work with gradle 6/7

@bamboo
Copy link
Author

bamboo commented Apr 21, 2021

I'm glad you found the solution, @guai. Thanks for sharing it here!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment