【问题标题】:What is the best way to parameterize a task on Gradle?在 Gradle 上参数化任务的最佳方法是什么?
【发布时间】:2016-10-14 14:10:05
【问题描述】:

如果它们不存在,我需要从两个不同的 .properties.dist 创建两个不同的 .properties 文件,因此我正在使用 Copy 任务并相应地指定 from 和 into。

目前我必须创建两个不同的任务,每个任务都创建一个像这样的文件:

task copyAndRenameDialling(type: Copy){
    if(!file("./properties/dialling.properties").exists()){

        from './dist/dialling.properties.dist'
        into './properties/'
        rename{ String fileName ->
            fileName.replace('.dist','')
        }
    }
}

task copyAndRenameFiles(type: Copy){
    if(!file("./properties/file.properties").exists()){

        from './dist/files.properties.dist'
        into './properties/'
        rename{ String fileName ->
            fileName.replace('.dist','')
        }
    }
}


task copyAndRenameProperties {
    dependsOn << copyAndRenameDialling
    dependsOn << copyAndRenameFiles
}

我使用 gradle copyAndRenameProperties 运行任务。 是否可以根据文件名将两个 Copy 任务参数化,以便我只有一个通用的 copyAndRename? 如果是这样,我怎样才能将参数传递给任务?

【问题讨论】:

  • 您真的需要将它们作为单独的任务,以便您可以单独调用它们,还是一项任务足以复制目标中不存在的文件?
  • 我不需要它们作为单独的任务,这就是我想分解它的原因。我想知道我是否可以使用相同的“任务”模式并使用两个不同的参数(即文件名)来做到这一点。

标签: gradle parameters task parameter-passing


【解决方案1】:

我会这样做:

task copyAndRenameProperties(type: Copy) {
    from 'dist'
    include '*.properties.dist'
    into 'properties'
    rename { it - ~/\.dist$/ }
    eachFile { if (file("properties/$it.name").file) it.exclude() }
}

或者如果你真的只想要这两个特定的文件

task copyAndRenameProperties(type: Copy) {
    from 'dist/dialling.properties.dist'
    from 'dist/file.properties.dist'
    into 'properties'
    rename { it - ~/\.dist$/ }
    eachFile { if (file("properties/$it.name").file) it.exclude() }
}

task copyAndRenameProperties(type: Copy) {
    from 'dist'
    include 'dialling.properties.dist', 'file.properties.dist'
    into 'properties'
    rename { it - ~/\.dist$/ }
    eachFile { if (file("properties/$it.name").file) it.exclude() }
}

【讨论】:

  • 我真的很喜欢第一个!我有两个问题: - “它”在哪里定义? - 什么是 rename... 语句?
  • rename { it - ~/\.dist$/ } 基本上是方法rename 的方法调用,带有闭包{ it - ~/\.dist$/ }。在带有一个参数的闭包中,如果您没有像在原始帖子中那样明确命名它,它被称为it。 rename 语句和你的一样,我的只是更紧凑一点,但它的作用是一样的。
猜你喜欢
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
相关资源
最近更新 更多