Search code examples
gradlebuilddependenciesbuild.gradlegradlew

Is there a way to get the version of a dependency from within build.gradle?


Here's my issue, I'm pulling latest.release based on the region that the project is in:

if (System.getenv()["namespace"].contains("dev")) {
       compile("com.foo.bar.dev:library:latest.release")
   } else if (System.getenv()["namespace"].contains("test")) {
       compile("com.foo.bar.test:library:latest.release")
   } else {
       compile("com.foo.bar.other:library:latest.release")
   }

Is there a way to resolve this dependency for a line later on that specifically wants to grab the jar version?

def zipFile = file("build/libs/foobar/library-${projectVersion}.jar")

Thanks for any assistance, the best I've found is dependencyInsight from the command line but I specifically need this automated in a task.


Solution

  • It looks like you just want to path of the resolved JAR. If I understood correctly, then you can resolve the configuration and filter the dependency you want. For example, using commons-lang3:

    dependencies {
        implementation("org.apache.commons:commons-lang3:3.11")
    }
    
    val commonsLang3Jar = configurations.compileClasspath.get().filter { it.name.startsWith("commons-lang3") }.singleFile
    
    println(commonsLang3Jar.absolutePath)
    

    This results in the following line being printed:

    ~/.gradle/caches/modules-2/files-2.1/org.apache.commons/commons-lang3/3.11/68e9a6adf7cf8eb7e9d31bbc554c7c75eeaac568/commons-lang3-3.11.jar