How do I exclude specific transitive dependencies of something I depend on?

You have a few options here. The most trivial is to put all excludes in one closure - if certain dependency is not in the transitives, the exclude clause will have no power. Using your code above:

dependencies {
    def withoutStuff = { 
        exclude group: 'com.android.support', module: 'support-v4' 
        exclude group: 'com.android.support', module: 'support-v13'
        exclude group: 'com.android.support', module: 'design-v13' 
    }

    // For Material Datepicker
    compile deps.datePicker, withoutStuff
}

Assuming you want to suppress “design-v13” in datepicker, but use if from foobar you may use 2 closures (closer to your original approach):

dependencies {
    def noSupport = { 
        exclude group: 'com.android.support', module: 'support-v4' 
        exclude group: 'com.android.support', module: 'support-v13'
    }
    def withoutStuff = { 
        delegate.configure(withoutSupport) // equivalent to:  noSupport.delegate=delegate; noSupport()
        exclude group: 'com.android.support', module: 'design-v13' 
    }    

    // For Material Datepicker
    compile deps.datePicker, noSupport
    compile deps.foobar, withoutStuff
}

And finally if you fancy another design you may use a higher order function to create the dependency config closure (depending on the build complexity and audience that may be overkill):

dependencies {
     // note that this is a closure returning closure
    def withExcludes = { boolean excludeDesign -> return { 
        exclude group: 'com.android.support', module: 'support-v4' 
        exclude group: 'com.android.support', module: 'support-v13'
        if (excludeDesign) {
          exclude group: 'com.android.support', module: 'design-v13' 
        }
    }}

    // For Material Datepicker
    compile deps.datePicker, withExcludes(true)
    compile deps.foobar, withExcludes(false)
}

I hope this helps - these are just illustrations of what you can do with the Gradle DSL. It is worth spending some time to understand the Gradle domain model, and then you can come up with your own variations.

1 Like