【问题标题】:Can we read command line arguments in settings.gradle?我们可以在 settings.gradle 中读取命令行参数吗?
【发布时间】:2021-08-12 02:29:20
【问题描述】:

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

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

【问题讨论】:

    标签: gradle multi-module


    【解决方案1】:

    您无法在设置 gradle 文件中读取整个命令行参数,但您可以执行 read project properties in settings file 并且可以使用命令行参数传递这些参数。

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

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

    注意带有选项 -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
    }
    

    【讨论】:

    • @Renatolvncic 这行得通。非常感谢。有义务
    最近更新 更多