在条件上应用Gradle配置

时间:2017-04-23 08:09:42

标签: gradle groovy build.gradle

我想仅在满足条件时才在Gradle脚本中应用配置:

useRepo = System.getenv()["IGNORE_REPO_CFG"] == null

buildscript {
    useRepo && repositories {  // <== HERE
        maven.url 'http://localhost:8081/artifactory/release'
    }
}

subprojects {
    configurations {
        all {
            useRepo && resolutionStrategy {  // <== HERE
                cacheChangingModulesFor 0, 'seconds'
                cacheDynamicVersionsFor 0, 'seconds'
            }
        }
    }
}

由于Groovy / Gradle范围魔法,我无法将useRepo传递给buildscriptsubprojects.configurations.all范围。

我读到了关于课堂包装的内容:

class Cfg {
    static final useRepo = System.getenv()["SA_IGNORE_REPO_CFG"] == null
}

但在Cfg.useRepo我得到了:

java.lang.ClassNotFoundException: Cfg

更新开:

project.ext.useRepo = System.getenv()["SA_IGNORE_REPO_CFG"] == null
buildscript {
    project.ext.useRepo && repositories {
        maven.url 'http://localhost:8081/artifactory/lognet-release'
    }
}

我得到了:

Caused by: groovy.lang.MissingPropertyException: Cannot get property 'useRepo' on extra properties extension as it does not exist

1 个答案:

答案 0 :(得分:1)

就像您尝试过的那样,您应该使用project.ext

project.ext.useRepo = System.getenv()["SA_IGNORE_REPO_CFG"] == null

但是当您现在尝试在project.ext内使用subprojects时,它是空的,因为它未在此项目中定义。所以你需要用``rootProject.ext`来访问它,因为你在那里定义它

subprojects {
    configurations {
        all {
            rootProject.ext.useRepo && resolutionStrategy {  // <== HERE
                cacheChangingModulesFor 0, 'seconds'
                cacheDynamicVersionsFor 0, 'seconds'
            }
        }
    }
}

您尝试使用ext中的buildscript,但这不起作用,因为首先执行buildscript - 闭包,然后执行另一个脚本。见this Gradle Discussion

如果要全部执行此操作,可以在gradle.ext内的settings.gradle上指定此变量。

gradle.ext.useRepo = System.getenv()["SA_IGNORE_REPO_CFG"] == null

然后使用它。

buildscript {
    gradle.ext.useRepo && repositories {
        maven.url 'http://localhost:8081/artifactory/lognet-release'
    }
}