build.gradle 文件中的 groovy - 如何交换 closures/methods

groovy in build.gradle file - how to swap closures/methods

正在寻找 groovy 专家来帮助我。在我的 android build.gradle 文件中我有

定义如下:

 apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply from: 'other.gradle'//this contains another flavor


//A method to detect if another gradle build file is available
def boolean isOtherBuildFile() {
     return new File('other.gradle').exists()
    }


    android {
        compileSdkVersion 21
        buildToolsVersion "21.1.1"

        defaultConfig {
            //blah blah not important
        }

        buildTypes {
            debug {
                //blah blah not important
            }

            release {
              //blah blah not important

            }
        }

            productFlavors {
                def STRING = "String"
                def BOOLEAN = "boolean"
//i'd like to be able to swap out this mock closure below with another one
                mock {
                    applicationId "org.example.mock"
                    versionName = "1.5" + '-mock'
                    buildConfigField STRING, GCM_SENDER_ID, '"123456789"'
                    buildConfigField STRING, BASE_ENDPOINT, '"localhost/"'
                }
              }

在名为 other.gradle 的文件中,我想将 mock 重新定义为其他东西。例如在 other.gradle 中我可以这样定义模拟:

 mock {
           applicationId "com.tutorial.mock"
           versionName = "2.4" + '-mock'
           buildConfigField STRING, GCM_SENDER_ID, '"987654321"'
           buildConfigField STRING, BASE_ENDPOINT, '"www.mymockdomain.com/"'
            }

所以这是我想要完成的:我想检查 puesdo 代码,如下:

if(isOtherBuildFile())
then
    //use the mock defined in other.gradle

else 
   //continue to use the mock defined in build.gradle

它在 android 工作室,但我不认为它是 android 与我希望的 groovy 语法有任何关系。我也同意换掉整个风味封闭装置,因为那是一个更好的解决方案。

应该足够了:

if(isOtherBuildFile() {
   project.apply: 'other.gradle'
} else {
   mock {}
}

你试过了吗?