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

Can we read command line arguments in settings.gradle?

我想在 settings.gradle 中读取命令行参数,这样我就可以只添加那些子模块,包括我正在传递的命令行。

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

You can't read whole command line arguments in settings gradle file, though what you can do is to read project properties in settings file and those can be passed with the command line arguments.

For example if you want to specify to include sub-project-1 in your Gradle build you would have to provide this value in a project property like following:

gradlew build -Pincluded.projects=sub-project-1

Note CLI command with option -P defines project 属性. It has to have specified key and value. In this case key is included.projects and value is sub-project-1.

In settings file you can read it with following getProperties() method on Project object. getProperties().get(String key).

Following is the settings script if you have sub modules with names:

  • sub-module-1
  • sub-module-2
  • sub-module-3

It will read 属性 that includes list of modules to include in build script. If 属性 is empty then all modules will be included, otherwise it selects passed in sub projects names and includes only present ones. There is no validation on sub project names.

// 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
}