Dave T.
Dave T.

Reputation: 1408

Gradle multi-project conditional dependencry

How would one create an Android Studio (Gradle) multi-project configuration such that projB depends on project(':projA') if projA is defined, but uses a file in libs/ otherwise?

Since it may be asked, in this case projA is an SDK; projB is a test application designed to demonstrate the SDK. If the SDK team gets a bug report, it often includes reproduction steps using projB.

When projB team does work, they do so on RC builds of projA, whereas the SDK team uses projB, with a dependency on project(':projA') so that a debug session can be run.

projB has no specific definition of its dependency on projA; that team takes the projA output from the build server and drops it in the libs/ folder, and has a wildcard dependency.

EDIT I finally went with this code in the dependencies closure, and it works like a charm:

def sdkRef

project.getRootProject().allprojects.each { proj ->
    if (proj.name.equals("Sdk")) {
        sdkRef = proj;
        return true;
    }
}

if (sdkRef) {
    println "SDK present in project; using project reference as dependency"
    compile sdkRef
} else {
    println "SDK is not present in project; using libs/"
}

Upvotes: 1

Views: 670

Answers (2)

ben75
ben75

Reputation: 28706

You can achieve that with productFlavors.

You just have to define:

  • 2 product flavors in projB/build.gradle
  • a specific dependency for each flavor

android {
    productFlavors {
        demo{}
        sdkdev{}
    }
    ...
}

dependencies{
    demoCompile files("libs/projectA.jar")
    sdkdevCompile project(":projectA")
    ...
}

The build will produce 2 apks.

In Android studio, someone from the demo team can run the demo flavor by selecting the "demoDebug" (or "demoRelease") variant (in Build Variant tab) and someone from sdk team will select the "sdkdevDebug" variant.

The gradle.settings must contains references for projA and projB, but a user from demo team will never have to compile projA because the demo flavor have no dependencies on it.

Upvotes: 1

loosebazooka
loosebazooka

Reputation: 2423

I wonder if that's something you can do with flavors and build variants.

Through code you might try in your build file :

dependencies {
 if (project.getRootProject().findProject(":projectA")) {
    compile project(":projectA")
  } else {
    compile files("libs/projectA.jar")
  }
}

One thing you have to consider is that your settings.gradle defines what modules are included in your project. So your two teams might end up with different files anyway for the project.

Upvotes: 1

Related Questions