Home > Software design >  How to include some deps and source codes in Gradle conditionally
How to include some deps and source codes in Gradle conditionally

Time:01-24

In a Maven project, it is easy to add extra deps and include extra source codes via defining a new Maven profile.

How to do the following things in a Gradle project.

  • Includes extra deps
  • Includes another source codes directory

And for example, use an extra property existence(eg. add to command line) to decide to activate it or not. I am not sure the best way in Gradle world.

CodePudding user response:

I am not recommending your approach.

But it can be done via - project properties from gradle command line and groovy if (condition) { } for dependencies and multiple sourceset defs

on command line

gradle build -PbProfile=extra1
ext.buildFlag = 'default'
if (project.hasProperty('bProfile')) {
    ext.buildFlag = property('bProfile')
}
println "running profile - ${buildFlag}"


dependencies {
    //common-deps
    if ("extra1".equals(buildFlag)) {
        //extra deps
    }
}

if ("extra1".equals(buildFlag)) {
    //custom sourceset def
} // more else if needed

CodePudding user response:

I use conditionally applied sub-configurations. This is done thru the apply from directive:

if (project.hasProperty('browsers')) {
  ext.browsers.split(',').each {
    def browser = it.trim()
    if (browser) {
      apply from: "${browser}Deps.gradle"
    }
  }
}

This block checks for specification of the browsers property (either from gradle.properties or the -P command line argument). If this property is defined, I split the property's value on commas and apply sub-configurations whose names conform to the pattern <browser>Deps.gradle.

The project in which I use this pattern is here

  • Related