groovy 获取rootPoject.name,或参考settings.gradle,了解包含的构建版本

uhry853o  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(189)

我使用includeBuild将我自己的库中的模块包含在settings.gradle中:

rootProject.name = "MyApp"
include ':app'

includeBuild '/usr/local/library/Android/Event'
includeBuild '/usr/local/library/Android/Location'
includeBuild '/usr/local/library/Android/Widget'

我知道我可以在后面重复这些语句:

gradle.includedBuilds.each{ includeBuild ->
    println includeBuild.name
}

但是,这将打印:

Event
Location
Widget

有没有一种简单的方法来获取我在每个库项目的settings.gradle文件中定义的rootProject.name
我知道我可以执行以下操作来给予替代名称:

includeBuild('/usr/local/library/Android/Event', {name = 'com.example.android.event'})
includeBuild('/usr/local/library/Android/Location', {name = 'com.example.android.location'})
includeBuild('/usr/local/library/Android/Widget', {name = 'com.example.android.widget'})

......但是,当我已经将它们定义为rootProject.name是它们各自的settings.gradle时,这是多余和麻烦的。
相反,我在寻找类似于以下内容的内容:

gradle.includedBuilds.each{ includeBuild ->
    println includeBuild.rootProject.name
}

例如,我知道includeBuild.projectDir,我能以某种方式获得对该目录中settings.gradle文件的(解析的)引用吗?

tcomlyy6

tcomlyy61#

我已经设法用org.gradle.tooling.GradleConnector解决了这个问题:

import org.gradle.tooling.GradleConnector
import org.gradle.tooling.ProjectConnection
import org.gradle.tooling.model.GradleProject

def getIncludedProjectNamesMap(Project project) {
    def projectNamesMap = new HashMap<String, String>()
    project.gradle.includedBuilds.each { includedBuild ->
        ProjectConnection connection = GradleConnector.newConnector()
                .forProjectDirectory(includedBuild.projectDir)
                .connect()
        GradleProject includedProject = connection.getModel(GradleProject.class);
        def name = includedProject.getName();
        connection.close();

        projectNamesMap.put includedBuild.name, name;
    }

    return projectNamesMap
}

println getIncludedProjectNamesMap(project)

...打印:

{Event=com.example.android.event, Location=com.example.android.location, Widget=com.example.android.widget}

......但这看起来相当慢,可能是由于它需要建立的所有连接。它目前可以完成这项工作,但我仍在寻找其他方法,如果可行的话。

相关问题