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



我有这个自定义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
    }
}

我想提取两个"from("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
}

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

它不工作。我对语法不太确定。这可能吗?有人能帮我弄对吗?

谢谢!

这只是一个大胆的猜测,但它可能与在静态上下文中定义规范有关。

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

最新更新