Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle - Add conditional classpath in buildscript dependencies

I have updated to Android Studio 2.2, which uses by default the Gradle Plugin v2.2.0, and is much better for debugging purposes. For disribution purposes, I must still use v2.1.3. I was thinking of adding a conditional command in the project gradle script, but I am not sure how to do it. The following test works

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        if (project.name.startsWith("X"))
        {
            classpath 'com.android.tools.build:gradle:2.1.3'
        }
        else
        {
            classpath 'com.android.tools.build:gradle:2.2.0'
        }
    }
}

But I need it to be something like

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        if (IS_RELEASE_VERSION)
        {
            classpath 'com.android.tools.build:gradle:2.1.3'
        }
        else
        {
            classpath 'com.android.tools.build:gradle:2.2.0'
        }
    }
}

and I cannot figure out how to do it. Thanks in advance

like image 261
lionscribe Avatar asked Sep 20 '16 20:09

lionscribe


People also ask

How do I force Gradle to use specific dependency?

If the project requires a specific version of a dependency on a configuration-level then it can be achieved by calling the method ResolutionStrategy. force(java. lang. Object[]).

How does Gradle resolve transitive dependencies?

Transitive dependencyBy default, Gradle resolves transitive dependencies automatically. The version selection for transitive dependencies can be influenced by declaring dependency constraints.

How do you avoid transitive dependencies in Gradle?

You can tell Gradle to disable transitive dependency management for a dependency by setting ModuleDependency.

What is Buildscript in Gradle?

Gradle builds a script file for handling two things; one is projects and other is tasks. Every Gradle build represents one or more projects. A project represents a library JAR or a web application or it might represent a ZIP that is assembled from the JARs produced by other projects.


1 Answers

Well, I believe I solved it, and it is very simple. You need to check the gradle.startParameter.taskNames property. Here is how I coded it:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        if (gradle.startParameter.taskNames.size() > 0 && gradle.startParameter.taskNames.get(0).contains("Release"))
        {
            classpath 'com.android.tools.build:gradle:2.1.3'
        }
        else
        {
            classpath 'com.android.tools.build:gradle:2.2.0'
        }
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

So far it is working fine. If you prefer, you can change the "Release" value, to a flavor variant (if you are using flavors).

like image 67
lionscribe Avatar answered Oct 17 '22 00:10

lionscribe