Is there a way to split/factor out common parts of Gradle build

若如初见. 提交于 2019-12-28 12:09:32

问题


We have several independent builds (each independent build is a multi-project build). The main build scripts become quite big as we have a set of common tasks reused by subprojects as well as there is a lot of repeation between indepedent builds. What we are looking for is:

  1. A way to split main build file into smaller files
  2. A way to reuse some parts of the build in other independent builds

What is the best way to achieve that in Gradle?


回答1:


Gradle 0.9 allows you to import a build script from another build script. Have a look at: Configuring the project using an external build script. Basically it's apply from: 'other.gradle'.

One thing the user guide doesn't mention is that the 'from' parameter can be a URL, so you can make your shared scripts available via HTTP somewhere (eg your subversion repository), and import them from multiple builds.




回答2:


The solution I found implies mapping the things you have in your other.gradle file.

def getVersionName = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'describe', '--tags'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}
ext{
    VERConsts = [:]
    VERConsts['NAME'] = getVersionName()
    VERConsts['NAME_CALL'] = getVersionName
}

Then, in your build.gradle file:

apply from: 'other.gradle'
// ...
android {
    defaultConfig {
        versionName VERConsts['NAME_CALL']()
        // or
        versionName VERConsts['NAME']
    }
}

Then, the versionName will have the call result.

Notes:

  • VERConsts['NAME'] = getVersionName() will call getVersionName() and store its result. Using it in your script e.g. versionName VERConsts['NAME'] will then assign the stored value.
  • VERConsts['NAME_CALL'] will instead store a reference to the function. Using VERConsts['NAME_CALL']() in your script will actually call the function and assign the result to your variable

The former will result in the same value being assigned across the script while the latter may result in different values (e.g. if someone pushes another version while your script is running).



来源:https://stackoverflow.com/questions/2566685/is-there-a-way-to-split-factor-out-common-parts-of-gradle-build

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