Better way to conditionally include dependencies?

In order to work around this issue (https://groups.google.com/forum/?fromgroups#!topic/adt-dev/Efpf87EoDQ0), I’m using one set of dependencies when I run tests, and another set of dependencies when I package an archive. Here’s my build.gradle file:

..
  apply from: 'dependencies.gradle'
          // <- enable this when building an .aar
// apply from: 'dependencies-test.gradle'
  // <- enable this when testing
  ..

and my dependencies.gradle file:

dependencies {
    ..
    compile 'org.codehaus.jackson:jackson-core-asl:1.9.2'
    compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.2'
}

and dependecies-test.gradle file:

dependencies {
    ..
    compile files('libs/jackson-core-asl-1.9.2.jar', 'libs/jackson-mapper-asl-1.9.2.jar')
}

and I currently have to manually comment/uncomment the correct dependencies file in build.gradle depending on what I’m doing.

Is there a way to tell gradle to use one set of dependencies when running “gradlew connectedInstrumentTest” and a different set of dependencies when running “gradlew uploadArchives”?

Wouldn’t be possible to have an if statements to apply one file or another? A condition could be controlled by a property set from a command line or in case you would like to distinguish connectedInstrumentTest and uploadArchives by checking gradle.startParameter.taskNames.

Thanks, that seems like a good hint!

Would you be able to point me to an example of checking gradle.startParameter.taskNames?

I’m new to gradle (but love it)

if (gradle.startParameter.taskNames.contains("connectedInstrumentTest")) {
  apply from: 'dependencies.gradle'
 } else ...

A drawback of using this construction is that you have to use this tasks names explicit in a command line. It would be better to use:

gradle.taskGraph.whenReady { graph ->
    if (graph.hasTask(developerBuild)) {
         ...
    }
}

which also detects tasks in a situation they are required by some other tasks (e.g. “gradle check” requires a test task), but the task execution graph is created after the configuration phase which is too late in your case (or at least you would have to do some manual operations on dependencies - which should be possible, but is more complicated).

2 Likes