Cleanest way in Gradle to get the path to a jar file in the gradle dependency cache

前端 未结 5 622
难免孤独
难免孤独 2021-02-05 00:36

I\'m using Gradle to help automate Hadoop tasks. When calling Hadoop, I need to be able to pass it the path to some jars that my code depends on so that Hadoop can send that de

5条回答
  •  忘掉有多难
    2021-02-05 01:40

    I recently had this problem as well. If you are building a java app, the problem at hand is normally that want to get the group:module (groupId:artifactId) to path-to-jar mapping (i.e. the version is not a search criteria as in one app there is normally only one version of each specific jar).

    In my gradle 5.1.1 (kotlin-based) gradle build I solved this problem with:

    var spec2File: Map = emptyMap()
    configurations.compileClasspath {
        val s2f: MutableMap = mutableMapOf()
        // https://discuss.gradle.org/t/map-dependency-instances-to-file-s-when-iterating-through-a-configuration/7158
        resolvedConfiguration.resolvedArtifacts.forEach({ ra: ResolvedArtifact ->
            s2f.put(ra.moduleVersion, ra.file)
        })
        spec2File = s2f.mapKeys({"${it.key.id.group}:${it.key.id.name}"})
        spec2File.keys.sorted().forEach({ it -> println(it.toString() + " -> " + spec2File.get(it))})
    }
    

    The output would be some like:

    :jing -> /home/tpasch/scm/db-toolchain/submodules/jing-trang/build/jing.jar
    :prince -> /home/tpasch/scm/db-toolchain/lib/prince-java/lib/prince.jar
    com.github.jnr:jffi -> /home/tpasch/.gradle/caches/modules-2/files-2.1/com.github.jnr/jffi/1.2.18/fb54851e631ff91651762587bc3c61a407d328df/jffi-1.2.18-native.jar
    com.github.jnr:jnr-constants -> /home/tpasch/.gradle/caches/modules-2/files-2.1/com.github.jnr/jnr-constants/0.9.12/cb3bcb39040951bc78a540a019573eaedfc8fb81/jnr-constants-0.9.12.jar
    com.github.jnr:jnr-enxio -> /home/tpasch/.gradle/caches/modules-2/files-2.1/com.github.jnr/jnr-enxio/0.19/c7664aa74f424748b513619d71141a249fb74e3e/jnr-enxio-0.19.jar
    

    After that, it is up to you to do something useful with this Map. In my case I add some --path-module options to my Java 11 build like this:

    val patchModule = listOf(
            "--patch-module", "commons.logging=" +
            spec2File["org.slf4j:jcl-over-slf4j"].toString(),
    
            "--patch-module", "org.apache.commons.logging=" +
            spec2File["org.slf4j:jcl-over-slf4j"].toString()
    )
    patchModule.forEach({it -> println(it)})
    
    tasks {
            withType {
                doFirst {
                    options.compilerArgs.addAll(listOf(
                            "--release", "11",
                            "--module-path", classpath.asPath
                    ) + patchModule)
                    // println("Args for for ${name} are ${options.allCompilerArgs}")
                }
            }
    }
    

提交回复
热议问题