How can I copy resolved dependencies to a new location, into dynamically created directories based on the dependencies details

Chris J :

I have a Java application that requires dependencies to be stored in specific locations (that is, it's not enough for gradle to just resolve them and add them to the classpath). This in an unfortunate application design, but something I cannot change.

I am using Gradle (required) to resolve the dependencies as follows:

configurations {
  myDeps
}

dependencies {
  myDeps group: 'foo.bar', name: 'baz', version: '1.0.0'
}

And copying them to a location using a Copy task:

task copyDeps(type: Copy) {
  from configurations.myDeps
  into "copyLocation"
}

This however, results in all dependencies stored flat in the "copyLocation", like: copyLocation/baz-1.0.0.jar when what I actually required is them stored in a structure like: copyLocation/foo/bar/baz/1.0.0/baz-1.0.0.jar

I have tried to use the eachFile method to dynamically set the path, but the FileCopyDetails passed to the closure only contains references to the filename (baz-1.0.0.jar).

The toString() of the FileCopyDetails contains the explicit path to where the dependency was retrieved from (and therefore all the info I need), but regex will be flaky given it can from from a number of sources, and will differ across user's machines e.g: It might be coming from my local Gradle cache

C:\Users\myUser\.gradle\caches\modules-2\files-2.1\foo.bar\baz\1.0.0\15d703651587fad0bb9d5s8c7b28d8b3b6a91x99\baz-1.0.0.jar

or maybe my local Maven repository

C:\whatever\path\to\myMavenRepo\foo\bar\baz\1.0.0\baz-1.0.0.jar

Thanks for any help!

Bjørn Vester :

If I understand you correctly, you want to copy the artifacts (jar files) of your declared dependencies into a folder that mirrors a Maven layout.

One way to do that is using Configuration.resolvedConfiguration and loop over the artifacts. Here is an example (using the Groovy DSL):

task copyDeps(type: Sync) {
    configurations.myDeps.resolvedConfiguration.resolvedArtifacts.each {
        def id = it.moduleVersion.id
        def groupFolders = id.group.replaceAll(/\./, "/")
        from(it.file) {
            into "$groupFolders/${id.name}/${id.version}/"
        }
        into "$buildDir/copyLocation"
    }
}

Note that I used a Sync task instead of Copy to ensure old files will be removed from the folder in case they are removed from the configuration.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166195&siteId=1