Skip to content

Instantly share code, notes, and snippets.

@melix
Last active Oct 7, 2022
Embed
What would you like to do?
Dependency downloader
// Downloads dependencies of an artifact in an output directory
//
// Note that it assumes _runtime_ dependencies, and it assumes "Maven compatible" variants.
// For compile time (API) dependencies, or for variant-aware resolution,
// code would have to be updated to set the appropriate resolution attributes.
//
// Usage:
// gradle download --input org.apache.groovy:groovy-json:4.0.1
//
// Optional flags:
// --output dir : path to output directory
// --transitive false : without transitives
// --sources true: also download sources
abstract class Downloader extends DefaultTask {
@OutputDirectory
@Optional
abstract DirectoryProperty getOutputDir()
@Option(option = "input", description = "GAV coordinates of the library")
@Input
abstract Property<String> getCoordinates()
@Input
@Optional
abstract Property<Boolean> getTransitive()
@Input
@Optional
abstract Property<Boolean> getSources()
private Configuration configuration = project.configurations.detachedConfiguration()
@Inject
protected abstract DependencyHandler getDependencies()
@Inject
protected abstract FileSystemOperations getFileOperations()
@Option(option = "output", description = "Output directory")
private void overrideOutputDir(String dir) {
outputDir.set(project.file(dir))
}
@Option(option = "transitive", description = "Download transitive dependencies")
protected void overrideTransitive(String flag) {
transitive.set(Boolean.valueOf(flag))
}
@Option(option = "sources", description = "Also download sources")
protected void overrideSources(String flag) {
sources.set(Boolean.valueOf(flag))
}
@TaskAction
void download() {
def cnf = configuration
def out = outputDir
configuration.transitive = transitive.get()
configuration.dependencies.add(dependencies.create(coordinates.get()))
fileOperations.copy {
from cnf
into out
}
if (Boolean.TRUE == sources.getOrElse(false)) {
fileOperations.copy { copy ->
copy.into out
def result = dependencies.createArtifactResolutionQuery()
.forComponents(cnf.incoming.resolutionResult.allComponents.collect { it.id })
.withArtifacts(JvmLibrary, SourcesArtifact)
.execute()
result.resolvedComponents.each {
it.getArtifacts(SourcesArtifact).each {
if (it instanceof ResolvedArtifactResult) {
copy.from it.file
}
}
}
}
}
println "Downloaded into ${outputDir.get()}"
}
}
repositories {
mavenCentral()
}
tasks.register("download", Downloader) {
transitive.convention(true)
outputDir.convention(coordinates.flatMap { layout.buildDirectory.dir("download/$it") })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment