How to emulate Android's productFlavors in a pure java gradle module?

喜你入骨 提交于 2021-02-18 12:28:12

问题


I need three flavors:

  • fake
  • staging
  • prod

fake will provide classes like FakeUser, FakeUserDb - it's very important that these classes are not compiled into the prod flavor.

prod and staging are completely identical, except that I need to compile a different String url into prod vs staging.

So, I need to create an "abstract" real flavor that both prod and staging inherit.

This can be easily done with the android gradle plugin, but how can I do it in a pure java gradle module?


回答1:


For each flavour you'll want to

  1. Create a SourceSet so it will be compiled
  2. Make the ${flavour}Compile Configuration extend the main compile configuration (see table 45.6 here for the configurations per SourceSet created by the java plugin)
  3. Create a JarTask (using the flavour as a classifier)
  4. Publish the jar artifact so the flavour can be referenced via the classifier

Something like:

def flavours = ['fake', 'staging', 'prod']
flavours.each { String flavour ->
    SourceSet sourceSet = sourceSets.create(flavour)
    sourceSet.java {
       srcDirs 'src/main/java', "src/$flavour/java"
    }
    sourceSet.resources {
       srcDirs 'src/main/resources', "src/$flavour/resources"
    }
    Task jarTask = tasks.create(name: "${flavour}Jar", type: Jar) {
       from sourceSet.output
       classifier flavour
    }
    configurations.getByName("${flavour}Compile").extendsFrom configurations.compile
    configurations.getByName("${flavour}CompileOnly").extendsFrom configurations.compileOnly
    configurations.getByName("${flavour}CompileClasspath").extendsFrom configurations.compileClasspath
    configurations.getByName("${flavour}Runtime").extendsFrom configurations.runtime

    artifacts {
       archives jarTask
    }
    assemble.dependsOn jarTask
}

Then, to reference one of the flavours in another project you could do one of the following:

dependencies {
   compile project(path: ':someProject', configuration: 'fakeCompile')
   compile project(path: ':someProject', configuration: 'fakeRuntime')
   compile 'someGroup:someProject:1.0:fake'
   compile group: 'someGroup', name: 'someProject', version: '1.0', classifier: 'fake'
}



回答2:


I wrote a gradle-java-flavours plugin to do this:

  • github project
  • JavaFlavoursPlugin.groovy
  • JavaFlavoursPluginTest.groovy


来源:https://stackoverflow.com/questions/37279281/how-to-emulate-androids-productflavors-in-a-pure-java-gradle-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!