首页 > 解决方案 > Gradle 不执行任务

问题描述

所以,这是我的毕业任务。我想将一些 sql 文件从 src/main/sql 复制到 build/sql,同时根据 .properties 文件过滤一些数据。

import org.apache.tools.ant.filters.ReplaceTokens
task buildSQL(type: Copy) {
    def db_names = ['oracle', 'postgresql', 'h2']
    db_names.each{db -> 
        copy {
            from('src/main/sql') 
            include '*sql'
            def properties = new Properties()
            file('src/main/sql/' + db + '_token.properties').withInputStream{
                properties.load(it);   
            }
            filter(ReplaceTokens, tokens: properties)
            rename 'vorlage', db
            into 'build/sql'
        }
    }
}

基本上这个任务在我运行时工作正常gradle buildSQL。当我运行gradle clean buildSQL任务时不会执行。

我该怎么做才能运行任务“buildSQL”?

标签: gradle

解决方案


该任务可能永远不会执行,因为它没有任何输入。唯一运行的是copy构建配置时的方法。

  • 当您只运行buildSQL任务时,该copy方法会在配置阶段运行,然后构建完成,因为没有输入任务。
  • 当您运行时clean buildSQL,该copy方法会在配置阶段运行,并且构建clean会在执行阶段执行任务——这会删除刚刚创建的副本。

如果我的解释没有立即意义,我建议阅读Gradle 的构建阶段。也许跑步gradle --console=verbose clean buildSQL也会对正在发生的事情有更多的了解。

抛开理论不谈,以下是修复配置的方法:

import org.apache.tools.ant.filters.ReplaceTokens
task buildSQL(type: Copy) {
    def db_names = ['oracle', 'postgresql', 'h2']
    db_names.each { db ->
        def properties = new Properties()
        file("src/main/sql/${db}_token.properties").withInputStream {
            properties.load(it)
        }
        from('src/main/sql') {
            include '*sql'
            filter(ReplaceTokens, tokens: properties)
            rename 'vorlage', db
        }
    }
    into 'build/sql'
}

换句话说,只需删除copy方法,但保留它CopySpecCopy任务。


推荐阅读