我们可以读取settings.gradle中的命令行参数吗?

San*_*aik 6 gradle multi-module

我想读取 settings.gradle 中的命令行参数,以便我可以仅添加那些包含我正在传递的命令行的子模块。

我们可以读取settings.gradle中的命令行参数吗?

Ren*_*cic 4

您无法读取设置 gradle 文件中的整个命令行参数,但您可以做的是读取设置文件中的项目属性,并且这些属性可以通过命令行参数传递。

例如,如果您想指定在 Gradle 构建中包含sub-project-1,则必须在项目属性中提供此值,如下所示:

gradlew build -Pincluded.projects=sub-project-1
Run Code Online (Sandbox Code Playgroud)

注意带有选项-P的 CLI 命令定义项目属性。它必须具有指定的键和值。在这种情况下,键是included.projects,值是sub-project-1

在设置文件中,您可以使用 Project 对象上的以下getProperties()方法来读取它。getProperties().get(String key)

如果您有具有名称的子模块,则以下是设置脚本:

  • 子模块1
  • 子模块2
  • 子模块3

它将读取包含要包含在构建脚本中的模块列表的属性。如果属性为空,则将包含所有模块,否则它将选择传入的子项目名称并仅包含当前的模块。没有对子项目名称进行验证。

// Define all the sub projects
def subprojects = ['sub-project-1', 'sub-project-2', 'sub-project-3'] as Set

// Read all subprojects from the project properties.
// Example of passed in project properties with Gradle CLI with the -P option
// `gradlew build -Pincluded.projects=sub-project-1,sub-project-3`
def includedProjectsKey="included.projects"
def projectsToIncludeInput = hasProperty(includedProjectsKey) ? getProperties().get(includedProjectsKey) : ""

Set<String> projectsToInclude = []
if(projectsToIncludeInput != "") {

  // Include passed in sub projects from project arguments
  projectsToIncludeInput.toString().split(",").each {
    projectsToInclude.add(it)
  }
} else {

  // Include all sub projects if none is specified
  projectsToInclude = subprojects
}

// Include sub projects
projectsToInclude.each {
  include it
}
Run Code Online (Sandbox Code Playgroud)