Skip to content Skip to sidebar Skip to footer

Change Dependency Through A Task In Gradle

I've build a lib, that in order to compile the application needs to set the specific flavor and release/debug type. However I'm trying to do this using a systemProperty when assem

Solution 1:

Well, what you do is just gambling. You do both, the setting of rootProject.ext.Production and the consuming of rootProject.ext.Production in the configuration phase. But I don't think there is some guarantee which is executed first the way you declared it. Besides that, using a JavaExec tasks configuration phase code to set some ext properties on the project is total non-sense anyway.

Instead of

task init(type: JavaExec){
    systemProperty "Production", System.getProperty("P")   //this variable comes from command variable
    rootProject.ext.set("Production", systemProperties["Production"]);
}

dependencies{
   if(rootProject.ext.Production=="flavor1"){
      releaseCompile "compile with flavor1"
   }else{
      releaseCompile "compile with flavor2"
   }
}

simply write

dependencies{
   if(System.properties.P == 'flavor1'){
      releaseCompile 'compile with flavor1'
   }else{
      releaseCompile 'compile with flavor2'
   }
}

or if you need it as variable on the rootProject because of subprojects needing the value in their build file

rootProject.ext.Production = System.properties.P;

dependencies{
   if(rootProject.Production == 'flavor1'){
      releaseCompile 'compile with flavor1'
   }else{
      releaseCompile 'compile with flavor2'
   }
}

If you just need it in the same build file multiple times, a local variable would also do, no need for a project ext-property

defproduction= System.properties.P;

dependencies{
   if(production == 'flavor1'){
      releaseCompile 'compile with flavor1'
   }else{
      releaseCompile 'compile with flavor2'
   }
}

Besides that, I wouldn't use a system property, but a project property. Just use

dependencies{
   if(production == 'flavor1'){
      releaseCompile 'compile with flavor1'
   }else{
      releaseCompile 'compile with flavor2'
   }
}

and call it with gradlew assembleRelease -P production=flavor1

Post a Comment for "Change Dependency Through A Task In Gradle"