Gradle / Groovy:将复制闭包移到单独的util方法

时间:2016-10-21 11:21:07

标签: gradle groovy

我有这个自定义gradle插件,它根据一些自定义规范创建一个tar文件:

tar.into("${project.name}-${project.version}"){
    into('lib'){
        from project.tasks.jar
        from project.configurations.runtime
    }

    //fix line endings for *.sh and *.conf files
    from("src/main/assembly"){
        include '**/*.sh'
        include '**/*.conf'
        filter(FixCrLfFilter, eol:FixCrLfFilter.CrLf.newInstance("unix")) // change line endings to unix format
        fileMode = 0744
        dirMode = 0755
    }

    //leave rest of the assembly untouched except for the filtered files above
    from("src/main/assembly"){
        exclude '**/*.sh'
        exclude '**/*.conf'
        fileMode = 0744
        dirMode = 0755
    }
}

我想从(" src / main / assembly")"中提取两个"阻塞到单独的util类中,以便我可以在另一个插件中重用它们。像这样:

class AssemblyUtil {

    def static CopySpec assemblyFiles = copySpec {
        //fix line endings for *.sh and *.conf files
        from("src/main/assembly"){
            include '**/*.sh'
            include '**/*.conf'
            filter(FixCrLfFilter, eol:FixCrLfFilter.CrLf.newInstance("unix")) // change line endings to unix format
            fileMode = 0744
            dirMode = 0755
        }

        //leave rest of the assembly untouched except for the filtered files above
        from("src/main/assembly"){
            exclude '**/*.sh'
            exclude '**/*.conf'
            fileMode = 0744
            dirMode = 0755
        }
    }
}

然后能够将原始方法重构为:

tar.into("${project.name}-${project.version}"){
    into('lib'){
        from project.tasks.jar
        from project.configurations.runtime
    }

    with AssemblyUtil.assemblyFiles
}

这样我可以在其他插件中重用闭包块。

它不起作用。我不确定语法。这可能吗?任何人都可以帮助我做对吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

只是一个疯狂的猜测,但它可能与在静态上下文中定义规范有关。也许以下工作可行:

class AssemblyUtil {

    def static CopySpec assemblyFiles(Project project) = project.copySpec {
        ...
    }
}

然后将项目传递给此方法

tar.into("${project.name}-${project.version}"){
    into('lib'){
        from project.tasks.jar
        from project.configurations.runtime
    }

    with AssemblyUtil.assemblyFiles(project)
}