首页 > 解决方案 > Jenkins 只执行 groovy 闭包的第一行

问题描述

我有以下两个类,它们在 groovy 本地工作得很好,但是一旦我将它们与 Jenkins 共享库一起使用,我就会遇到一些问题。

./模板.groovy

class Template {
    String arch
    String type
    def body = {}

    Template(type, arch, body) {
        this.arch = arch
        this.type = type
        this.body = body
    }
}

./TemplateBook.groovy

import Template

class TemplateBook {
    def templates = []

    TemplateBook() {
        def template = new Template("test", "lnx", { args -> sh('echo "Hello World!"'); sh("echo Test"); sh("echo $args")})
        templates.push(template)
    }

    def getTemplate(type, arch) {
        def template
        for (def i = 0; i < templates.size(); i++) {
            if (templates[i].arch == arch && templates[i].type == type) {
                template = templates[i].getBody()
                i = templates.size()
            }
        }
        return template
    }
}

直接使用就Template.body可以正常工作(在本地和在 Jenkins 上),但使用TemplateBook.getTemplate()only 执行闭包的第一行(主体)。

def templateBook = new TemplateBook()
def body = templateBook.getTemplate("test", "lnx")

body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = this
body("test")

输出:
世界你好!

def template = new Template("type", "arch", { args -> sh('echo "Hello World!"'); sh("echo Test"); sh("echo $args")})

def body2 = template.body
body2.resolveStrategy = Closure.DELEGATE_FIRST
body2.delegate = this
body2("test")

输出:
世界你好!
测试
测试

标签: jenkinsgroovyclosures

解决方案


推荐阅读