How can I use Gradle to download dependencies and

2019-01-20 17:01发布

问题:

I would like to use Gradle to download dependencies and their source files and place them all in one directory. I found this answer below that tells me how to do it for the dependencies themselves, but I would like to also get the source files. How do I do that?

I know that the Eclipse plugin can grab source files, but I don't know where it places them.

How can I use Gradle to just download JARs?

回答1:

This works

apply plugin: 'java'

repositories { ... }

dependencies {
    compile 'foo:bar:1.0'
    runtime 'foo:baz:1.0'
}

task download {
    inputs.files configurations.runtime
    outputs.dir "${buildDir}/download"
    doLast {
        def componentIds = configurations.runtime.incoming.resolutionResult.allDependencies.collect { it.selected.id }
        ArtifactResolutionResult result = dependencies.createArtifactResolutionQuery()
            .forComponents(componentIds)
            .withArtifacts(JvmLibrary, SourcesArtifact)
            .execute()
        def sourceArtifacts = []
        result.resolvedComponents.each { ComponentArtifactsResult component ->
            Set<ArtifactResult> sources = component.getArtifacts(SourcesArtifact)
            println "Found ${sources.size()} sources for ${component.id}"
            sources.each { ArtifactResult ar ->
                if (ar instanceof ResolvedArtifactResult) {
                    sourceArtifacts << ar.file
                }
            }
        }

        copy {
            from configurations.runtime
            from sourceArtifacts
            into "${buildDir}/download"
        }
    }
}


回答2:

apply plugin: 'java'

configurations {
    runtimeSources
}

dependencies {
    compile 'foo:bar:1.0'
    runtime 'foo:baz:1.0'

    configurations.runtime.resolvedConfiguration.resolvedArtifacts.each { ResolvedArtifact ra ->
        ModuleVersionIdentifier id = ra.moduleVersion.id
        runtimeSources "${id.group}:${id.name}:${id.version}:sources"
    }
}

task download(type: Copy) {
    from configurations.runtime
    from configurations.runtimeSources
    into "${buildDir}/download"
}


标签: java gradle jar